0

I've written the following source code:

ifstream leggiFile;
leggiFile.open("Questions.txt",ios::in);

if (!leggiFile.good())
{
  cerr << "\n\n\n\tErrore during file opening Questions.txt\n\n\n" << endl;
}
else
{
    // ...
};

leggiFile.close();
system("pause");

Now I'd like to use the same object for working with a second file.

leggiFile.open("Answers.txt",ios::in);

i=0;
if(!leggiFile.good())
{
  cerr << "\n\n\n\tError during opening of file answers.txt\n\n\n" << endl;
}
else
{
    // ...
}

Problem: The 2nd time the file cannot be opened and the error message appears. Why? Could you please suggest me a solution?

jrok
  • 54,456
  • 9
  • 109
  • 141
Uwe_98
  • 697
  • 1
  • 8
  • 21

2 Answers2

2

It's possible that you've done work on the stream that set one or more of the error flags, such as eofbit.

Closing the stream doesn't clear its error flags, you have to do it manually. Call leggiFile.clear(); after you close it.

Since C++11, this is done automaticaly by open(), though. If you're already using a C++11 compiler, your problem is elsewhere (can't say where, you haven't shown enough code).

jrok
  • 54,456
  • 9
  • 109
  • 141
  • Starting with C++11, a successful call to `open` will call `clear`. – Pete Becker Apr 05 '13 at 18:48
  • @PeteBecker Didn't know that, thanks. I updated the A to make that clear. – jrok Apr 05 '13 at 18:53
  • Dear jrok, Thank You very much. It worked immegiately. I'm using visual C++ 2008 Express version. With that its also possible writing pure C++ code. The version of the C++ compiler I don't know. – Uwe_98 Apr 06 '13 at 17:48
  • @Uwe_98 Glad it helped. It's common courtesy on Stack Overflow to accept answers that helped you ([How does accepting an answer work](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)). Btw, C++11 is pure C++, it just refers to the specific version of ISO standard for the language. Read more [here](http://en.wikipedia.org/wiki/C%2B%2B11). Greetz. – jrok Apr 06 '13 at 18:28
0

Learn singleton design pattern for logging or any multiple access to any file. You can also use Mutex lock so that code will be waited for resources like files. But it is not wise to use same file simultaneously. File can be open for a lyfecycle of code. It is not a issue.

pcbabu
  • 2,219
  • 4
  • 22
  • 32
  • Maybe I didn't express myself well. I opened one file, then I closed it and I opened a second file with the same stream. Anyway my problem is solved by using stream.clear(). Thank You. – Uwe_98 Apr 06 '13 at 17:55