0

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

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What you probably mean is that your code is not portable across different endian-ness or integral sizes, which leads to using a "one-at-a-time" conversion approach, however it is still faster even doing that than reading text format.
What do you mean by not portable ? If you mean endianness and different size for int types, I try to write a class with template parameters to take that into account during reading. I can't use "text" files because I have already more than 1 Po of binary files on a supercomputer and I can't even imagine how much it would weight in "text" mode... So do you have a more portable version than raw binary files ?
@Vincent - Yes, I mean endianess, size, and alignment. As I said, you must have solved those problems already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.