C ++ how to store an integer in a binary file?

I have a structure with 2 integers and I want to save 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 someone tell me what the problem is?

+4
source share
5 answers

You probably want to reset fout before reading from it.

To clear a stream, do the following:

 fout.flush(); 

The reason for this is that fstreams usually want to buffer output as long as possible to reduce cost. To make the buffer empty, you call flush in the stream.

+5
source

When storing integers in files, you can use the htonl() , ntohl() family of functions to make sure that they will be read in the correct format regardless of whether the file is written on a large end machine and read later on a small machine. These functions are intended for use on the network, but may be useful when writing to files.

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

Probably,

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

Be warned that your method involves information about the size and content of your integers and the packaging of your structures, none of which will be necessarily true if your code is transferred to another machine.

For reasons of mobility, you want to have output procedures that display structure fields separately, as well as output numbers with specific bitrates with specific content. This is why there are serialization packages.

0
source

try the following:

 fout.write((const char*)&p, sizeof(pw)); fin.read((char*)&q, sizeof(pw)); 

instead

 fout.write((const char*)p, sizeof(pw)); fin.read((char*)q, sizeof(pw)); 

vagothcpp (yournotsosmart ++ programmer = p)

0
source

Source: https://habr.com/ru/post/1305010/


All Articles