是否未在追加模式下定义 tellp()

whether tellp() not defined in append mode?

本文关键字:tellp 下定义 模式 追加 是否      更新时间:2023-10-16

我在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 filen";
    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();
Visual

C++ 2015 编译的应用打印 0、30、10、32。

可能是您拥有C++标准库版本中的错误。您使用什么编译器?