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

标签 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

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

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

为什么没有列出 block #2 和 #3?

谢谢

最佳答案

函数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
}

// ...

关于C++ 使用 gcount() 方法读/写随机访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28241568/

相关文章:

c++ - 为什么在读取时发现 eof 时会设置故障位?

c++ - 具有文件处理和 istringstreams 的无限循环

c++ - fstream 在 Qt Creator 中不起作用

c++ - getline 不读取文件或从文件返回

c++ - 如何在 Visual C++ 2010 中使用 C++ 库

c++ - 用 boost spirit 解析交错行

c++ - 从有符号字符到整数的值初始化,过早提升?

c++ - 如何使用 fstream 写入 C++ 中可执行文件目录上方的文件?

c++ - 使用 openMPI 发送对象

c++ - 函数调用出错