在文件中设置位置且无法读回

Set position in file and cannot read it back

我创建一个文件,我将读写位置都移动到5,我读回位置,得到的是一个无效位置。为什么?

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string fname = "test.txt";

    {
        fstream fs(fname);
        fs << "abcdefghijklmnopqrstuvwxyz";
    }

    fstream fs(fname);
    streamoff p = 5;

    fs.seekg(p, ios_base::beg);
    fs.seekp(p, ios_base::beg);

    const streamoff posg = fs.tellg();
    const streamoff posp = fs.tellp();

    cerr << posg << " = " << posp << " = " << p << " ???" << endl;

    return 0;
}

结果:

-1 = -1 = 5 ???

您没有正确创建文件,因此您打开文件进行读写时没有指定打开选项,在这种情况下,它认为文件已经存在,因此无法打开。

  • 第二个错误是将字符串传递给 fstream 的 open 函数,该函数采用 const 字符串,结果失败,因此您使用字符串的 c_str 将其转换为 char* 成员函数。

拇指法则总是检查打开是否成功。

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{

    string fname = "test.txt";

    fstream fs(fname.c_str(), ios::out | ios::in | ios::binary | ios::trunc);
    if(fs.fail())
        cout << "Failed to open file" << endl;
    fs << "abcdefghijklmnopqrstuvwxyz";

    streamoff p = 5;

    fs.seekg(p, ios_base::beg);
    fs.seekp(p, ios_base::beg);

    const streamoff posg = fs.tellg();
    const streamoff posp = fs.tellp();

    cerr << posg << " = " << posp << " = " << p << " ???" << endl;

    fs.close();

    return 0;
}
  • 请注意,如果您不使用我的打开标志 (ios::trunc, out, in),只需在您的项目目录中手动创建一个名为 "test.txt" 的文件即可。

问题是您的文件从一开始就没有正确写入,因为您使用的是 std::fstream,它在打开一个默认模式为 ios::out|ios::in 的不存在的文件时失败(请参阅std::basic_filebuf::open and the default parameters used with std::basic_fstream::open).

要修复它,只需在写入文件时使用 std::ofstream 而不是 std::fstream

{
  ofstream fs(fname);
  fs << "abcdefghijklmnopqrstuvwxyz";
}