Pietro
Pietro

Reputation: 13172

Set position in file and cannot read it back

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

Answers (2)

mindriot
mindriot

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

Raindrop7
Raindrop7

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 second mistake you pass a string to fstream's open function which takes a const string the result it fails so you convert it to char* with string's c_str member function.

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;
}
  • note if you don't my open flags (ios::trunc, out, in) just create manually a file named "test.txt" in your project directory.

Upvotes: 1

Related Questions