shortint
shortint

Reputation: 17

Why does tellp() give -1?

I'm trying to learn about fstream and here is the code that I'm running on VS2019:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

using namespace std;

int main() {
    //cout << "lOOKING IN FILE";
    string s;
    fstream dictionary("C:/Users/source/repos/Test2/Test2/Text.txt");
    if (!dictionary) // were there any errors on opening? 
        exit(-1);
    while (dictionary >> s) cout << s << '\n'; // Print all names in file
    dictionary.seekp(0, ios::beg); // Go back to beginning of file
    cout << dictionary.tellp() << endl; 
    dictionary >> s;
    cout << s; // Print the first name
    return 0;
}

The output is:

abc
acb
cab
-1
cab

Why does tellp give -1 and not go to beginning of file?

Upvotes: 1

Views: 285

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409442

You need to clear the state of the stream.

Once the state of a stream have changed from good (i.e. when it reaches end-of-file or there's a failure) then you can't operate on the stream again without clearing the state.

Upvotes: 3

Related Questions