Bruno Giannotti
Bruno Giannotti

Reputation: 323

Weird program behavior when streaming data to files before using seekg and tellg

I'll try to be as clear as I can: Whenever I try to stream data to my file before my 'do' loop and my pointers reading and writing, my program goes nuts! It appears to be running an infinite loop.

fstream fileHandler; //Can also be done via constructor fstream fileHanlder("myData.txt", ios::out);
//fileHandler.open("myData.txt", ios::out);//Default is in AND out

fileHandler.open("test.txt", ios::in | ios::binary | ios::out);

if (fileHandler.is_open()) {

    //fileHandler << "anything" <---HERE IS THE PROBLEM
    cout << "The file has been opened and edited properly.";

    fileHandler.seekg(0, ios::end);
    streampos sizeOfFile = fileHandler.tellg();//tellg returns type streampos
    fileHandler.seekg(0, ios::beg);

    do{
        string buffer;
        fileHandler >> buffer;
        cout << buffer << endl;

    }while(!fileHandler.eof());

    if ((fileHandler.rdstate()^ifstream::eofbit) == 0) {
        fileHandler.clear();
        cout << fileHandler.tellg() << endl;
    }


    fileHandler.close();

} else cout << "There was a problem opening the file!";

My file has nothing but a simple phrase.

EDIT: fixed the title according to new information Thanks for any attention!

Upvotes: 1

Views: 66

Answers (1)

Bruno Giannotti
Bruno Giannotti

Reputation: 323

Removing the binary flag fixed it for some reason.

Upvotes: 1

Related Questions