C/C++ [C++] Reading a binary file into a byte array

Click For Summary
Reading a binary file into a byte array can be effectively achieved using a vector of char in C++. While some resources recommend using char* or char[], a vector offers easier retrieval of byte blocks. There is a slight overhead associated with vectors due to their internal structure, but they can still be integrated with legacy code by passing a pointer to the vector's data. For instance, using &vectorofchar[0] allows compatibility with functions expecting a pointer. Overall, using a vector of char is a practical choice for managing binary data in C++.
Silicon Waffle
Messages
160
Reaction score
203
I have to read a binary file into a byte array and chop it wherever I like.
I'd like to use a vector of char to do this. But reading some resources from known people, I find they tend to use char* or char []. Using a vector of chars seems easier for retrieval of any block of bytes.
Which means of storage would be better to you ? Thank you.
 
Technology news on Phys.org
Silicon Waffle said:
I have to read a binary file into a byte array and chop it wherever I like.
I'd like to use a vector of char to do this. But reading some resources from known people, I find they tend to use char* or char []. Using a vector of chars seems easier for retrieval of any block of bytes.
Which means of storage would be better to you ? Thank you.

When you say "vector", do you mean "array"? If so, your mention of char[] applies...
 
I mean C++'s vector class.
 
There's a small amount of overhead for a vector, since there's a local structure, that contains a pointer to the allocated memory (as well as other parameters like the object type and number of objects). When combining old and new code, sometimes I'll use a vector in the main code, but call an old code function that takes a pointer to object as a parameter. For example, if I have vector <char> vectorofchar ..., I use &vectorofchar[0] as a parameter for the old code function.
 
  • Like
Likes Silicon Waffle
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 26 ·
Replies
26
Views
4K
  • · Replies 8 ·
Replies
8
Views
6K
  • · Replies 57 ·
2
Replies
57
Views
5K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
10
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 5 ·
Replies
5
Views
8K
  • · Replies 29 ·
Replies
29
Views
3K
  • · Replies 75 ·
3
Replies
75
Views
6K