我创建了一个文件,我将读取和写入位置都移动到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 ???
答案 0 :(得分:1)
你没有正确创建文件所以你打开一个文件进行读写而没有指定打开的选项,在这种情况下它认为文件已经存在,因此无法打开。
#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;
}
答案 1 :(得分:1)
问题是你的文件从来没有被正确写入,因为你使用的是std::fstream
,当打开一个不存在的文件时,它的默认模式为ios::out|ios::in
会失败(参见{{} 3}}和std::basic_filebuf::open
使用的默认参数。)
要解决此问题,请在编写文件时使用std::ofstream
代替std::fstream
:
{
ofstream fs(fname);
fs << "abcdefghijklmnopqrstuvwxyz";
}