问题写入二进制文件C整数++ [英] Problems writing an integer to binary file C++
问题描述
我使用fstream的写入二进制文件的一个整数。
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;
}
问题是在线f1.write。我可以写二进制文件的数组,但是当我尝试INT它给了我一个错误写的只是一个块:
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:
在0x522C7EA6(msvcp120d.dll)在Project.exe未处理的异常:0000005:访问冲突读取位置0x00000002
我不明白是什么问题。
推荐答案
您需要转换的地址的 NUM
到的char *
,而不是 NUM
本身。事实上,使用的结果的行为(字符*)NUM
是未定义的这解释了崩溃。
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.
使用 f1.write((字符*)试验#,的sizeof(NUM));
来代替。更改 f1.read
与此类似。
Use f1.write((char *)&num, sizeof(num));
instead. Change f1.read
similarly.
我也改变了的sizeof
参数:我preFER这种风格,因为它面向未来,你对类型的变化。移动的,你需要考虑的字节序的如果你正在写在不同的平台(例如Windows和Linux)。阅读
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).
这篇关于问题写入二进制文件C整数++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!