Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Handling with files

Hi!
I can't understand what is wrong to my code:

#include <fstream>

using namespace std;

int main() {
char c, inputString[10000];
int i=0;

ifstream infile("in.txt");
while (infile.get(c)) inputString[i++]=c;
infile.close();

infile.open("out.txt");
if (!infile.good()) return 0;
system("Pause");
return 0;
}

The problem is that this program can not open file "out.txt" (such file exists on disc) and so returns at line `if... return 0`. If I remove line `while...` from the code, everything works fine (file "out.txt" can be opened). Why is it so??
[648 byte] By [TheVAL] at [2007-11-11 10:05:46]
# 1 Re: Handling with files
I think the proper way for checking for opening errors is:
infile.open("c:\\2.txt");
if(! infile.is_open()) return 0;
I hope this helps.
Viorel at 2007-11-11 20:59:33 >
# 2 Re: Handling with files
OK, this helps in this situation which I made as small as possible, but not in my real situation.. Now I have such code:

#include <fstream>
#include <iostream>

using namespace std;

int main() {
char c, inputString[10000];
int i=0;

ifstream infile("in.txt");
ofstream outfile("out.txt");
for (int j=0;j<10000;j++) inputString[j] = 0;
while (infile.get(c)) inputString[i++]=c;
outfile << inputString;
outfile.close();
infile.close();

infile.open("out.txt");
if (!infile.is_open()) return 0;
outfile.open("res.txt");
for (int j=0;j<10000;j++) inputString[j] = 0;
while (infile.get(c)) {
cout <<c;
inputString[i++]=c;
}

outfile <<inputString;
infile.close();
outfile.close();
system("Pause");
return 0;
}

And now the problem is as follows - when cheching if infile is open, everything is ok, infile is open and we go further. But we never go into this second while loop.. althouht there are some simbols written in file "out.txt". I think maybe it thinks we have already reached end of infile.. but how can that be, we have just opened this file.. The correct action would be going into this second while loop and printing out one by one all characters in file "out.txt".
TheVAL at 2007-11-11 21:00:27 >
# 3 Re: Handling with files
OK, I found a solution - I had to write "infile.clear()" before reopening it.
TheVAL at 2007-11-11 21:01:32 >