【发布时间】:2018-07-01 18:28:22
【问题描述】:
我在 C++ 中试验文件指针。在下面的代码中,得到的结果是 0、30、10 和 12。所以这意味着如果我们做 seekp(),tellp() 在追加模式下不会给出正确的结果。我期待 tellp() 在 seekp() 和附加数据之后给我 32。我知道在应用程序模式下,写作总是到最后,因此产生了这个疑问。结果是否意味着tellp()位置在追加模式下无关紧要?
h1.txt 文件的内容是:01234567891011121314151617181911 和预期的一样。
ofstream f1("h1.txt",ios::app|ios::out);
if (!f1)
{
cerr<<"cannot open the file\n";
exit(-1);
}
currentPos = f1.tellp();
cout<<"Initial Write Pointer Position = "<<currentPos<<endl;
// Write some data at the end
for(int index=0;index<20;index++)
{
f1<<index;
}
currentPos= f1.tellp();
cout<<"Write Pointer Position after write = "<<currentPos<<endl;
f1.seekp(10);
currentPos= f1.tellp();
cout<<"Write Pointer Position after seek = "<<currentPos<<endl;
/** Note: Even if you reposition pointer, in app mode, data will always be written to the end */
f1<<11;
currentPos= f1.tellp();
/** seekp does not match. In app mode, data is writtten to end */
cout<<"Final Write Pointer Position after seek and write = "<<currentPos<<endl;
f1.close();
【问题讨论】:
-
在写入完成之前完成对文件末尾的查找(作为写入调用的一部分)。
-
但是写完之后为什么tellp()给出12?为什么不是32?这是否意味着 append 根本不更新这个指针。它与tellp()完全无关
标签: c++ c++11 file-handling