Vincent
Vincent

Reputation: 60481

How to read an array in a binary file in C++

Currently I read arrays in C++ with ifstream, read and reinterpret_cast by making a loop on values. Is it possible to load for example an unsigned int array from a binary file in one time without making a loop ?

Thank you very much

Upvotes: 0

Views: 5163

Answers (1)

Robᵩ
Robᵩ

Reputation: 168876

Yes, simply pass the address of the first element of the array, and the size of the array in bytes:

// Allocate, for example, 47 ints
std::vector<int> numbers(47);

// Read in as many ints as 'numbers' has room for.
inFile.read(&numbers[0], numbers.size()*sizeof(numbers[0]));

Note: I almost never use raw arrays. If I need a sequence that looks like an array, I use std::vector. If you must use an array, the syntax is very similar.

The ability to read and write binary images is non-portable. You may not be able to re-read the data on another machine, or even on the same machine with a different compiler. But, you have that problem already, with the solution that you are using now.

Upvotes: 3

Related Questions