写二进制文件(C ++)整数 [英] writing integer to binary file (C++)
问题描述
我有一个很简单的问题,这恰好是我很难,因为这是我第一次尝试用二进制文件的工作,我不太了解他们。所有我想要做的是写一个二进制文件的一个整数。
下面是我做的:
的#include<&的fstream GT;
使用命名空间std;
诠释主(){
INT NUM = 162;
的ofstream文件(file.bin,IOS ::二进制);
file.write((字符*)试验#,的sizeof(NUM));
file.close();
返回0;
}
你能告诉我,如果我做错了什么,和什么?
这是给我麻烦的部分是与file.write行了,我不明白。
感谢您提前。
这是给我麻烦的部分是与file.write行,我不知道
理解这一点。
块引用>如果你读
ofstream.write()
方法的文档,你会看到,它要求两个参数:
在指针数据块的内容写入;
一个整数值,再presenting在字节大小,这一块的
这个声明只是给这两条信息,以
ofstream.write()
:file.write(reinter pret_cast<为const char *>(试验#)的sizeof(NUM));
试验#
是数据块的地址(在这种情况下,仅仅是一个整数变量),的sizeof(NUM)
是该块(如Windows平台上的4个字节)的大小。I have a very simple question, which happens to be hard for me since this is the first time I tried working with binary files, and I don't quite understand them. All I want to do is write an integer to a binary file.
Here is how I did it:
#include <fstream> using namespace std; int main () { int num=162; ofstream file ("file.bin", ios::binary); file.write ((char *)&num, sizeof(num)); file.close (); return 0; }
Could you please tell me if I did something wrong, and what?
The part that is giving me trouble is line with file.write, I don't understand it.
Thank you in advance.
解决方案The part that is giving me trouble is line with file.write, I don't understand it.
If you read the documentation of
ofstream.write()
method, you'll see that it requests two arguments:
a pointer to a block of data with the content to be written;
an integer value representing the size, in bytes, of this block.
This statement just gives these two pieces of information to
ofstream.write()
:file.write(reinterpret_cast<const char *>(&num), sizeof(num));
&num
is the address of the block of data (in this case just an integer variable),sizeof(num)
is the size of this block (e.g. 4 bytes on Windows platforms).这篇关于写二进制文件(C ++)整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!