gpt4 book ai didi

c++ - seekp 和 seekg 不适用于 fstream

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:04 27 4
gpt4 key购买 nike

我在 Debian x64 PC 上运行的 c++ 程序有一个奇怪的行为。

我无法设法先读取文件,然后写入另一个值,然后再读取这些值。我已经阅读了很多信息,包括关于 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;
}

谁能告诉我发生了什么,我该怎么做才能解决这个问题?

最佳答案

对于 fstream (std::basic_filebuf),单个文件位置由 seekp()seekg( )

不可能独立地跟踪putget 位置。

类模板std::basic_filebuf 保存单个文件位置

§ 27.9.1.1

  1. The class basic_filebuf associates both the input sequence and the output sequence with a file.

  2. The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library FILEs.

  3. In particular:

    • If the file is not open for reading the input sequence cannot be read.
    • If the file is not open for writing the output sequence cannot be written.
    • A joint file position is maintained for both the input sequence and the output sequence.

关于c++ - seekp 和 seekg 不适用于 fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187297/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com