是否在追加模式中定义了tellp()?

时间:2018-01-23 02:16:07

标签: c++ c++11 file-handling

我正在用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();

1 个答案:

答案 0 :(得分:1)

Visual C ++ 2015编译应用程序打印0,30,10,32。

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