C++使用GCONTTYER()方法读写随机存取文件

C++使用GCONTTYER()方法读写随机存取文件,c++,fstream,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() &g

以代码为例:

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
现在,假设我想做一件无用的事情:读取每个块,然后在同一个文件中再次写入。实际上,这是一个什么都不做的操作

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
为什么块2和块3没有列出

谢谢

函数在输出序列上搜索,但输出序列没有改变,因为您刚才读取的内容改变了输入序列

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

// ...

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++中最大的困惑之一是在文件中既有输入也有输出,Sekp和SeCKG是一样的东西,就像Telp和Telg一样。
Block #1: 1048576 bytes
// ...

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
}

// ...