Reputation: 13172
I create a file, I move both read and write position to 5, I read the position back, and what I get is an invalid position. Why?
#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;
}
Result:
-1 = -1 = 5 ???
Upvotes: 1
Views: 437
Reputation: 5668
The problem is that your file is never written correctly in the first place, because you are using a std::fstream
, which fails when opening a nonexistent file with its default mode of ios::out|ios::in
(see std::basic_filebuf::open
and the default parameters used with std::basic_fstream::open
).
To fix it, just use a std::ofstream
instead of a std::fstream
when writing the file:
{
ofstream fs(fname);
fs << "abcdefghijklmnopqrstuvwxyz";
}
Upvotes: 1
Reputation: 3911
you are not creating file correctly so you are opening a file for read and write without specifying the options for opening in this case it consider the file already exists thus it fails to open.
the law a thumb is always check if opening was successful or not.
#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;
}
Upvotes: 1