Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

fstream file writes in the file

2004-09-21
2012-09-26
  • Thanks a lot, VH.

    Frenky

     
  • Well, it seems that this is really an annoying bug. I wrote in my file the text:

    MOTHER

    and the program:

    include <iostream>

    include <fstream>

    include <cstring>

    include <iomanip>

    using namespace std;
    int main()
    {
    fstream file("myfile.txt", ios::in | ios::out);
    if(file.is_open())
    {
    string input;
    for(int i=0;i!=10;i++)
    {
    file.seekg(ios :: beg);
    input.clear();
    file.clear();
    getline(file,input);
    cout<<i<<" "<<input.size()<<" "<<input<<endl;

    }
    }
    else cerr << "Error" <<endl<<endl;
    system("pause");
    }

    works just fine. But, when I added some more text in new lines in my file:

    MOTHER
    FROM
    PINK
    FLOYD

    • the program started to change my file, as before.

    Any idea what's wrong?

     
  • Jim W.
    Jim W.
    2004-09-21

    Try opening the file in binary mode (add | ios::binary ). Also, it might help to close the file ( file.close(); )

    Any of that help?

    -- Jim.

     
  • Thanks, Jim. I've added ios::binary - and the file is not changed if I run my program for several times. It works.

    Frenky