file stream problem

this code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>

int main()
{
	using namespace std;

	char ch;
	ifstream infile;
	ofstream outfile;

	infile.open("test.txt");
	
	if(infile)
	{
		cout << "file contains:" << endl;
		while((ch = infile.get()) != EOF)
			cout << ch;
		cout << endl;
		cout << "end of file" << endl;
	}
	infile.close();

	outfile.open("test.txt", ios::app);

	if(outfile)
	{
		cout << "inpute test then insert EOF to save" << endl;
		while((ch = cin.get()) != EOF)
			outfile.put(ch);
	}
	outfile.close();

	infile.open("test.txt");
	if(infile)
	{
		cout << "file contains" << endl;
		while(infile.get(ch))
			cout << ch;
	}

	return 0;
}

isn't working right.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
file contains:
this is a sample text editor, it allowes the simple creation of text files and t
he appending to those text files.

there is but one way to use such a usless program. as practice and nothing more.

that is all, tab <tab>          that is tab.
hello world
hello

end of file
inpute test then insert EOF to save
some text
^Z
Press any key to continue . . .


it reads the file the first time just fine.
then i input "some text" and it writes it just fine.
however when i reuse the "infile" stream it doesn't work.
idk why, i closed it and everything.

this bothers me cause similar code was in my book and it did the same thing, i just ignored it at the time. now i want to solve the problem.
When you reach the EOF of the file, it sets a bit that isn't reset when you open a new file. You need to use the .clear() like this:

1
2
3
4
5
    outfile.close();

    infile.clear(); //add this
    infile.open("test.txt");
    if(infile)
thank you.
figured it was something like that, after looking at the stream with the debuger it didn't really look like it was err... "clean" after the close.

thanks again.
Topic archived. No new replies allowed.