【问题标题】:whether tellp() not defined in append mode?tellp() 是否未在附加模式下定义?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我使用 MinGW 附带 Codeblocks 16.01 安装。让我换个编译器试试看。
  • 是的,这似乎是编译器问题。我也下载了 Visual Studio 并按预期工作。让我提出这个问题(我使用的是 TDM-GNU 4.9.2 64 位)
猜你喜欢
  • 2018-02-12
  • 2020-05-12
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多