seekp和seekg don';我不能使用fstream 我在Debian X64 PC上运行的C++程序中有一个奇怪的行为。

seekp和seekg don';我不能使用fstream 我在Debian X64 PC上运行的C++程序中有一个奇怪的行为。,c++,fstream,C++,Fstream,我无法先读取文件,然后再写入另一个值,然后再读取这些值。 我已经阅读了很多信息,包括关于stackoverflow的问题,发现(也通过实验)我需要同时更改seekp和seekg,我这样做了。 一切正常。。。直到我从小溪里读到什么。在读操作之后,如果我在文件的开头搜索,然后调用tellg(),tellp(),它们都返回'-1' 测试代码: void testFstreamSeekp() { fstream in("file", ios::in | ios::out); cout

我无法先读取文件,然后再写入另一个值,然后再读取这些值。 我已经阅读了很多信息,包括关于stackoverflow的问题,发现(也通过实验)我需要同时更改seekp和seekg,我这样做了。 一切正常。。。直到我从小溪里读到什么。在读操作之后,如果我在文件的开头搜索,然后调用tellg(),tellp(),它们都返回'-1'

测试代码:

void testFstreamSeekp() {
    fstream in("file", ios::in | ios::out);

    cout << "g: " << in.tellg() << endl;
    cout << "p: " << in.tellp() << endl;

    in.seekp(0, ios_base::end);

    cout << "endp g: " << in.tellg() << endl;
    cout << "endp p: " << in.tellp() << endl;

    in.seekp(0, ios_base::end);
    in.seekg(0, ios_base::end);

    cout << "end g: " << in.tellg() << endl;
    cout << "end p: " << in.tellp() << endl;

    in.seekp(0, ios_base::beg);
    in.seekg(0, ios_base::beg);

    cout << "beg g: " << in.tellg() << endl;
    cout << "beg p: " << in.tellp() << endl;

        // Everything is fine until here (that is tellp() == 0, tellg() == 0)
    int a, b;
    in >> a >> b;
    cout << "a: " << a << endl << "b: " << b << endl;

        // tellg() == -1, tellp() == -1 ?????????!!!!!!!!!!
    cout << "read g: " << in.tellg() << endl;
    cout << "read p: " << in.tellp() << endl;

    in.seekp(0, ios_base::beg);
    in.seekg(0, ios_base::beg);

        // tellg() == -1, tellp() == -1 ?????????!!!!!!!!!!
    cout << "beg g: " << in.tellg() << endl;
    cout << "beg p: " << in.tellp() << endl;
}
void testfstreamsekp(){
fstream-in(“文件”,ios::in | ios::out);
cout对于
fstream
std::basic_filebuf
),单个文件位置由
seekp()
seekg()移动

独立跟踪
put
get
位置是不可能的

类模板
std::basic_filebuf
保持一个文件位置

§27.9.1.1

  • 类basic_filebuf将输入序列和 用一个文件输出序列

  • 对读写一个由计算机控制的序列的限制 类basic_filebuf的对象与读取和 使用标准C库文件编写

  • 特别是:

    • 如果文件未打开以读取,则无法读取输入序列
    • 如果文件未打开以进行写入,则无法写入输出序列
    • 输入序列和输出序列都保持一个关节文件位置

  • seekp()/seekg()
    如果流处于错误状态,则无法工作。您的文件看起来如何?您是否已检查它是否已成功打开?Jrok,为什么不将其作为答案发布?您解决了我的问题,谢谢。Fstream在读取数据后处于eof()状态。我已清除流(in.clear())现在它的工作原理就像charm。相关:这正是我所说的“我需要同时更改seekp和seekg”。无论如何,谢谢你,POW,现在我知道我只需要使用一个函数(它们中的任何一个)来移动两个指针。