Reading a 64-bit integer file

I am trying to learn C ++ by writing some kind of code by itself and is very new in this field.

I am currently trying to read and write a 64 bit integer file. I am writing a 64 bit integer file as follows:

ofstream odt; odt.open("example.dat"); for (uint64_t i = 0 ; i < 10000000 ; i++) odt << i ; 

Can someone help me read this 64 bit integer file (one by one)? So, the distant examples that I found are read line by line, not one at a time.

Edit:

 ofstream odt; odt.open("example.dat"); for (uint64_t i = 0 ; i < 100 ; i++) odt << i ; odt.flush() ; ifstream idt; idt.open("example.dat"); uint64_t cur; while( idt >> cur ) { cout << cur ; } 
+4
source share
2 answers

If you must use a text file, you need to highlight something to separate the formatted values. spaces for example:

 ofstream odt; odt.open("example.dat"); for (uint64_t i = 0 ; i < 100 ; i++) odt << i << ' '; odt.flush() ; ifstream idt; idt.open("example.dat"); uint64_t cur; while( idt >> cur ) cout << cur << ' '; 

However, I highly recommend using the lower level iostream methods ( write() , read() ) and writing them in binary format.

An example using read / write data and binary data (is there a 64-bit htonl / ntohl equiv btw ??)

 ofstream odt; odt.open("example.dat", ios::out|ios::binary); for (uint64_t i = 0 ; i < 100 ; i++) { uint32_t hval = htonl((i >> 32) & 0xFFFFFFFF); uint32_t lval = htonl(i & 0xFFFFFFFF); odt.write((const char*)&hval, sizeof(hval)); odt.write((const char*)&lval, sizeof(lval)); } odt.flush(); odt.close(); ifstream idt; idt.open("example.dat", ios::in|ios::binary); uint64_t cur; while( idt ) { uint32_t val[2] = {0}; if (idt.read((char*)val, sizeof(val))) { cur = (uint64_t)ntohl(val[0]) << 32 | (uint64_t)ntohl(val[1]); cout << cur << ' '; } } idt.close(); 
+1
source

Do you mean something like this?

 ifstream idt; idt.open("example.dat"); uint64_t cur; while( idt>>cur ) { // process cur } 
0
source

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


All Articles