Weird thing with fstream

G

gukn9700

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("test.txt", ios_base::in | ios_base::eek:ut);
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Not able to open file in C++ 9
fstream Buffers 26
fstream File i/o 1
problem with fstream 3
fstream tests 3
Can I append text to a file? 2
eof error using '>>' in fstream 2
fstream - write a file 3

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top