开发者

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.

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. Can anyone tell me what is the problem?


You probably want to flush fout before you read from it.

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. To force the buffer to be emptied, you call flush on the stream.


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. The functions were intended for network use, but can be valuable when writing to files.


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

Should probably be

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜