C ++使用gcount()方法读/写随机访问文件

时间:2015-01-30 17:37:58

标签: c++ fstream

考虑代码:

const int length = 1024 * 1024; //     1048576
char buffer[length];

fstream f;

int main(int argc, char *argv[])
{
    f.open("file.bin", ios::in | ios::out | ios::binary);

    f.read(buffer, length);

    int k = 0;
    while (f.gcount() > 0)
    {
        k++;
        cout << "Block #" << k << ": " << f.gcount() << " bytes" << endl;

        f.read(buffer, f.gcount());
    } // while

    f.close();

    return 0;

} // main

文件“file.bin”的大小为2,895,872字节。 当我运行此代码时,输​​出为:

Block #1: 1048576 bytes
Block #2: 1048576 bytes
Block #3: 798720 bytes

现在,假设我想做一件无用的事情:读取每个块,然后在同一个文件中再次写入(实际上这是一个无操作的操作)

const int length = 1024 * 1024; //     1048576
char buffer[length];

fstream f;

int main(int argc, char *argv[])
{
    f.open("file.bin", ios::in | ios::out | ios::binary);

    f.read(buffer, length);

    int k = 0;
    while (f.gcount() > 0)
    {
        k++;
        cout << "Block #" << k << ": " << f.gcount() << " bytes" << endl;

// this is the code I added
        f.seekp(-f.gcount(), ios_base::cur); // move file pointer backwards
        f.write(buffer, f.gcount()); // write the buffer again <=> do nothing
// end of the code I added

        f.read(buffer, f.gcount());
    } // while

    f.close();

    return 0;

} // main

现在输出

Block #1: 1048576 bytes

为什么未列出#2和#3块?

谢谢

1 个答案:

答案 0 :(得分:0)

函数seekp寻找输出序列,但输出序列由于您刚刚读取(改变输入序列)而没有改变。

我认为每次执行读取时最好更新输出序列,我不确定它是否可行,但您可以尝试:

// ...

f.read(buffer, length);
f.seekp(f.gcount(), ios_base::cur); // update output sequence

int k = 0;
while (f.gcount() > 0)
{
    k++;
    cout << "Block #" << k << ": " << f.gcount() << " bytes" << endl;

// this is the code I added
    f.seekp(-f.gcount(), ios_base::cur); // move file pointer backwards
    f.write(buffer, f.gcount()); // write the buffer again <=> do nothing
// end of the code I added

    f.read(buffer, f.gcount());
    f.seekp(f.gcount(), ios_base::cur); // update output sequence
}

// ...
相关问题