views:

165

answers:

5

i gt a struct with 2 integer, 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;}  

my output is 0. anyone can tell me what is the problem?

+5  A: 

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.

sharth
ops.. sori.. wrong typing... i'm actually using fin.read... tq..
blaxc
If I add the flush command, it works properly.
sharth
woot! i get it ad by flushing the fout... tq very much... can i know why i need to flush it?
blaxc
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.
sharth
A: 
fin.write((char*)q, sizeof(pw));  

Should probably be

fin.read((char*)q, sizeof(pw));  
Tuomas Pelkonen
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
A: 

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.

swestrup
+1  A: 

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.

J. Fritz Barnes
A: 

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