简体   繁体   中英

Writing integers in a binary file in C++

Assume that I want to write integers into a file and read them later on. Am I under the right impression that the only way to make sure each integer occupies exactly 4 bytes in the file is to write them in a binary file?

Using std::ofstream , you can do something like:

 std::ofstream os("myfile.bin", std::ios::binary); 
 int x = 42;
 os.write(reinterpret_cast<char*>(&x), sizeof(x)); 

Reading is done by std::ifstream::read in exactly the same way. You must cast where you are reading/writing to a char * since that is the type read and write expects.

Using sizeof will work for integers that aren't 4 bytes too, but of course, you can't read 4 byte integers on a machine that has 2-byte integers, or vice versa.

Of course, if you want your storage to be "portable", you would need to care about byte-order. But if you are doing this for storing some data on the local machine, that doesn't matter.

You're right, assuming that it's a 32 bit integer.

If you write it to the file as an integer, it will be unreadable by a text editor, but will take exactly your integer's size.

why do you need to write integers into file as binary format not plain text?

each integer exactly occupy 4-byte => this depends on how big your integer is, if you are sure that all your integers can be expressed in 4-byte. And this has nothing to do with forcing file format to be binary. You can directly using plain text file to store your integers. However if you want your file be more compact, you can try binary file.

And it's more easy to implement batch reading using binary file. But I doubt whether you need that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM