本文介绍了Tellp()是否未在追加模式下定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++尝试文件指针.在下面的代码中,获得的结果为0、30、10和12.因此,如果我们执行seekp(),则tellp()在追加模式下不会给出正确的结果.我期望tellp()在seekp()和附加数据之后给我32.我了解,在应用程序模式下,写作总是到最后,因此引起了这个疑问.结果是否意味着在附加模式下tellp()的位置无关紧要?

I was experimenting with file pointers in C++. In below code, the result obtained is 0, 30, 10 and 12. So it means that tellp() does not give correct result in append mode if we do seekp(). I was expecting tellp() to give me 32 after seekp() and appending data. I understand that in app mode, writing is always to the end and hence got this doubt. Does the result mean that tellp() position does not matter in append mode?

h1.txt文件的内容为:01234567891011121314151617181911,与预期的一样.

The contents of h1.txt file is : 01234567891011121314151617181911 and is is as expected.

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();

推荐答案

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

Visual C++ 2015 compiled app prints 0, 30, 10, 32.

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

Could be a bug in the version of C++ standard library you have. What compiler are your using?

这篇关于Tellp()是否未在追加模式下定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 00:34