考虑代码:
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/