读取64位整数文件

时间:2012-11-24 09:56:22

标签: c++ file-io uint64

我正在尝试通过自己编写一些代码来学习C ++,并且在这个领域非常新。

目前,我正在尝试读取和写入64位整数文件。我按以下方式写64位整数文件:

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

有人可以帮助我如何读取64位整数文件(逐个)吗?所以,我发现的很多例子都是逐行读取,而不是一个一个整数。

编辑:

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 ;
}

2 个答案:

答案 0 :(得分:3)

如果必须使用文本文件,则需要某些内容来描述格式化值的分离。空格例如:

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 << ' ';

话虽这么说,我会强烈建议使用较低级别的iostream方法(write()read())并以二进制形式写这些。

使用读/写和二进制数据的示例(是否有64位的htonl / ntohl等效?)

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 :(得分:0)

你的意思是这样的吗?

ifstream idt;
idt.open("example.dat");
uint64_t cur;
while( idt>>cur ) {
  // process cur
}
相关问题