blaxc
blaxc

Reputation: 73

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?

Upvotes: 4

Views: 3549

Answers (5)

vagothcpp
vagothcpp

Reputation: 1

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)

Upvotes: 0

J. Fritz Barnes
J. Fritz Barnes

Reputation: 928

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.

Upvotes: 4

swestrup
swestrup

Reputation: 4209

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.

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 82026

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.

Upvotes: 5

Tuomas Pelkonen
Tuomas Pelkonen

Reputation: 7831

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

Should probably be

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

Upvotes: 0

Related Questions