Weird thing with fstream

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • gukn9700

    Weird thing with fstream

    When I used fstream to handle a file, I met with a very weird thing:

    #include <fstream>
    #include <iostream>

    using namespace std;

    int main()
    {
    fstream outfile;

    outfile.open("t est.txt", ios_base::in | ios_base::out);
    if (!outfile)
    {
    cout << "open file fail!\n";
    return -1;
    }

    //display original text
    char ch;
    while (outfile.get(ch ))
    {
    cout << ch;
    }
    cout << '\n';
    outfile.clear() ; //clear eofbit

    //seek to end of the text
    outfile.seekp(0 , ios_base::end);
    //get input from the user and append it to outfile
    while (cin.get(ch))
    {
    outfile.put(ch) ;
    }

    outfile.close() ;
    return 0;
    }

    the content of test.txt is:

    This is a text
    only for test.

    But after I ran the program, it turned out to be:

    ThThis is a text
    only for test.
    abcdefg

    The "abcdefg" was the input. But, where did the additional "Th" come
    from?

    What's wrong with my program?

    Compiler: gcc3.2.3
    System: Windows2000
    Compile option: -ansi -Wall
  • Jim Fischer

    #2
    Re: Weird thing with fstream

    gukn9700 wrote:[color=blue]
    > When I used fstream to handle a file, I met with a very weird thing:
    >
    > [code snipped]
    >
    > the content of test.txt is:
    >
    > This is a text
    > only for test.
    >
    > But after I ran the program, it turned out to be:
    >
    > ThThis is a text
    > only for test.
    > abcdefg
    >
    > The "abcdefg" was the input. But, where did the additional "Th" come
    > from?
    >
    > What's wrong with my program?
    >
    > Compiler: gcc3.2.3
    > System: Windows2000
    > Compile option: -ansi -Wall[/color]

    Hmmm... That's odd. Your program looks OK to me, and it works as
    expected when compiled with G++ 3.3 on a Red Hat 9 Linux box.

    Just out of curiosity, what happens if you specify the 'binary' mode
    flag when the program opens the text file, i.e.,

    outfile.open ("test.txt", ios_base::out | ios_base::binar y);

    --
    Jim

    To reply by email, remove "link" and change "now.here" to "yahoo"
    jfischer_link58 09{at}now.here. com


    Comment

    Working...