4

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?

1
  • fin.write? fin.read, surely. Is this real code? And you might want to flush/close the output stream before opening the file for input.
    – CB Bailey
    Mar 24, 2010 at 14:42

5 Answers 5

5

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.

2
  • woot! i get it ad by flushing the fout... tq very much... can i know why i need to flush it?
    – blaxc
    Mar 24, 2010 at 14:48
  • I added some comments about that in the answer. Basically, fstreams are buffered objects. You need to flush that buffer before the file itself will have the data in it.
    – Bill Lynch
    Mar 24, 2010 at 14:54
4

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.

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

Should probably be

fin.read((char*)q, sizeof(pw));  
1
  • i ad changed it... i'm actually using fin.read instead of fin.write... so.. what's the problem here? tq for ur respond..
    – blaxc
    Mar 24, 2010 at 14:45
0

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.

0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.