简体   繁体   English

C ++如何将整数存储到二进制文件中?

[英]C++ how to store integer into a binary file?

I've got a struct with 2 integers, and I want to store them in a binary file and read it again. 我有一个包含2个整数的结构,我想将它们存储在二进制文件中并再次读取。

Here is my code: 这是我的代码:

static const char *ADMIN_FILE = "admin.bin";
struct pw {  
  int a;  
  int b;
};

void main(){  
  pw* p = new pw();  
  pw* q = new pw();  
  std::ofstream fout(ADMIN_FILE, ios_base::out | ios_base::binary | ios_base::trunc);  
  std::ifstream fin(ADMIN_FILE, ios_base::in | ios_base::binary);  
  p->a=123;  
  p->b=321;  
  fout.write((const char*)p, sizeof(pw));  
  fin.read((char*)q, sizeof(pw));  
  fin.close();  
  cout << q->a << endl;
}  

The output I get is 0 . 我得到的输出是0 Can anyone tell me what is the problem? 谁能告诉我这是什么问题?

You probably want to flush fout before you read from it. 你可能想在读取它之前冲洗fout

To flush the stream, do the following: 要刷新流,请执行以下操作:

fout.flush();

The reason for this is that fstreams generally want to buffer the output as long as possible to reduce cost. 原因是fstream通常希望尽可能长时间地缓冲输出以降低成本。 To force the buffer to be emptied, you call flush on the stream. 要强制清空缓冲区,请在流上调用flush。

When storing integers to files, you can use the htonl() , ntohl() family of functions to ensure that they will be read back in the correct format regardless of whether the file is written out on a big-endian machine, and read back later on a small-endian machine. 将整数存储到文件时,可以使用htonl()ntohl()系列函数来确保以正确的格式回读它们,无论文件是否在big-endian机器上写出,并回读后来在一台小端机器上。 The functions were intended for network use, but can be valuable when writing to files. 这些功能旨在用于网络,但在写入文件时可能很有用。

fin.write((char*)q, sizeof(pw));  

应该是

fin.read((char*)q, sizeof(pw));  

Be warned that your method assumes things about the size and endianness of your integers and the packing of your structures, none of which is necessarily going to be true if your code gets ported to another machine. 请注意,您的方法假定整数的大小和字节顺序以及结构的包装,如果您的代码被移植到另一台机器,则这些都不一定是真的。

For portability reasons, you want to have output routines that output the fields of structures separately, and that output numbers at specific bitwidths with specific endianness. 出于可移植性的原因,您希望输出例程分别输出结构字段,并输出具有特定字节序的特定位宽的数字。 This is why there are serialization packages. 这就是为什么有序列化包。

try this: 试试这个:

fout.write((const char*)&p, sizeof(pw));  
fin.read((char*)&q, sizeof(pw));  

instead of 代替

fout.write((const char*)p, sizeof(pw));  
fin.read((char*)q, sizeof(pw));  

vagothcpp (yournotsosmartc++programmer=p) vagothcpp(yournotsosmartc ++ programmer = p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM