I am trying to learn C++ by writing some code by my own and very new in this field.
Currently, I am trying to read and write a 64 bit integer file. I write 64 bit integer file in following way:
ofstream odt;
odt.open("example.dat");
for (uint64_t i = 0 ; i < 10000000 ; i++)
odt << i ;
Can anybody help me how to read that 64 bit integer file (one by one) ? So, far examples I have found, that reads line by line, not one by one integer.
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 ;
}
If you must use a text file, you need something to delineate the separation of 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 << ' ';
That being said, I would strongly advise you use lower level iostream methods ( write()
, read()
) and write these in binary.
Sample using read/write 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();
You mean something like this?
ifstream idt;
idt.open("example.dat");
uint64_t cur;
while( idt>>cur ) {
// process cur
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.