First of all, for the try block to do something good, you need to include exceptions for the stream.
Secondly, a loop like:
while (! myfile.eof() )
It will not cause trouble, and you will see it here. The problem (in this case) is that when the file does not open, eof will never be signaled - you cannot / do not go to the end of the file because there is no file. Thus, your cycle runs forever, in an existentialist search for the end of a nonexistent file. Fix the loop and things get better in a hurry:
char buffer[256]; ifstream myfile ("test.txt"); while (myfile.getline(buffer,100)) { cout << buffer << endl; }
While you are on it, a little more corrections will not hurt (if you really do not want to use less than half of the space that you allocated for your buffer):
char buffer[256]; ifstream myfile ("test.txt"); while (myfile.getline(buffer,sizeof(buffer))) { cout << buffer << endl; }
Or, of course, completely fix the problem:
std::string buffer; ifstream myfile("test.txt"); while (getline(myfile, buffer)) cout << buffer << "\n";
Edit: Note that none of these (at least for the time being) are dependent on exceptions in general. They are configured to write a line to the output if we can read the line from the input. If the file does not open, the body of the loop simply will not execute, because we cannot read from the file that was not opened. If we want to print an error message informing the user that the file does not open, we will have to process it separately from what is indicated above. For example:
ifstream myfile("test.txt"); if (!myfile) { std::cerr << "File failed to open"; return FAIL; } while (std::getline(myfile
Jerry Coffin
source share