Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
blaxc Avatar asked Jan 23 '23 09:01

blaxc


1 Answers

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.

like image 65
Bill Lynch Avatar answered Jan 25 '23 23:01

Bill Lynch