在文件中设置了位置,不能读取它

Set position in file and cannot read it back

本文关键字:不能 不能读 读取 位置 文件 设置      更新时间:2023-10-16

我创建了一个文件,我将读和写位置都移动到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字符串,结果失败,因此你将其转换为char*与string的c_str成员函数。

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

#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::openstd::basic_fstream::open使用的默认参数)。

要解决这个问题,只需在写入文件时使用std::ofstream而不是std::fstream:

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