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

时间:2016-10-06 17:43:34

标签: c++ stream fstream

我创建了一个文件,我将读取和写入位置都移动到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 ???

2 个答案:

答案 0 :(得分:1)

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

  • 你把字符串传递给fstream的开放函数的第二个错误,它取一个const字符串,结果失败,所以你用字符串&#39; s 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),只需手动创建一个名为&#34; test.txt&#34;的文件。在你的项目目录中。

答案 1 :(得分:1)

问题是你的文件从来没有被正确写入,因为你使用的是std::fstream,当打开一个不存在的文件时,它的默认模式为ios::out|ios::in会失败(参见{{} 3}}和std::basic_filebuf::open使用的默认参数。)

要解决此问题,请在编写文件时使用std::ofstream代替std::fstream

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