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

Writing integer to binary file using C++?(使用 C++ 将整数写入二进制文件?)
本文介绍了使用 C++ 将整数写入二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,这对我来说很困难,因为这是我第一次尝试使用二进制文件,但我不太了解它们.我要做的就是将一个整数写入二进制文件.

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.

我是这样做的:

#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?

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

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

提前谢谢你.

推荐答案

给我带来麻烦的部分是file.write,我没有明白了.

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

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

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

  1. 一个指向数据块的指针,其中包含要写入的内容;

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

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

这条语句只是将这两条信息提供给ofstream.write():

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

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

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

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

这篇关于使用 C++ 将整数写入二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)