Problems writing an integer to binary file C++

China☆狼群 提交于 2020-01-07 03:07:55

问题


I am using fstream to write an integer to binary file.

int main(){

fstream f1;
int num = 2, num2 = 0;

f1.open("dat1", ios::app | ios::out | ios::in | ios::binary);

f1.write((char *)num, sizeof(int));
f1.seekp(0);
f1.read((char *)num2, sizeof(int));

cout << num2;

}

The problem is on line f1.write. I can write to binary file an array, but when I try to write just one block of int it gives me an error:

Unhandled exception at 0x522C7EA6 (msvcp120d.dll) in Project.exe: 0xC0000005: Access violation reading location 0x00000002.

I don't understand what the problem is.


回答1:


You need to cast the address of num to char*, not num itself. In fact, the behaviour of using the result of (char*)num is undefined which explains the crash.

Use f1.write((char *)&num, sizeof(num)); instead. Change f1.read similarly.

I've also changed the sizeof argument: I prefer that style as it future-proofs you against type changes. Moving on, you'll need to consider endianness if you're writing and reading in different platforms (e.g. Windows and Linux).




回答2:


You need this:

f1.write((char *)&num, sizeof(int));
f1.seekp(0);
f1.read((char *)&num2, sizeof(int));

write() and read() want a pointer to where your data is.

int num = 2;

Using (char *)num converts num to a pointer pointing at address 0x00000002.


Also, when working with binary files (other than testing) it is always best to include a header, which should at least contain the following:

  • A Magic Number (usually 4 bytes), so the exact file type can be determined or checked regardless of what the extention might be.

  • A version number, which will allow you to extend the format and structure of your file in the future without breaking your current format.

  • As others already stated, a Byte Order Mark which will allow your data to be read in correctly on all platforms (Little-endian / Big-endian).




回答3:


The line should actually be:

f1.write((char *)&num, sizeof(int));

You need an address as an argument to the write function. Check out http://www.cplusplus.com/reference/ostream/ostream/write/.




回答4:


write want's a array. This means the start address. (char *)num this converts the number to a address and will point to a point you don't want. Use &num to get the address of num. Maybe make a cast with (char*) too.



来源:https://stackoverflow.com/questions/34612069/problems-writing-an-integer-to-binary-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!