使用 C++ 将整数写入二进制文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9244563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:31:57  来源:igfitidea点击:

Writing integer to binary file using C++?

c++binaryintegerfstream

提问by eqagunn

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.

给我带来麻烦的部分是file.write,我不明白。

Thank you in advance.

先感谢您。

回答by

The part that is giving me trouble is line with file.write, I don't understand it.

给我带来麻烦的部分是file.write,我不明白。

If you read the documentation of ofstream.write()method, you'll see that it requests two arguments:

如果您阅读ofstream.write()方法文档,您会看到它需要两个参数:

  1. a pointer to a block of datawith the content to be written;

  2. an integer value representing the size, in bytes, of this block.

  1. 一个指针的数据块与要写入的内容;

  2. 一个整数值,表示此块大小(以字节为单位)

This statement just gives these two pieces of information to ofstream.write():

该声明仅将这两条信息提供给ofstream.write()

file.write(reinterpret_cast<const char *>(&num), sizeof(num));

&numis 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 32-bit platforms).

&num是数据块的地址(在这种情况下只是一个整数变量),sizeof(num)是该块的大小(例如,在 32 位平台上为 4 个字节)。