Can Errors occur while opening a file?
I'll repeat a point I made in the previous section :
When you open a file using ofstream (which means output), you can write data to the file. You could say it's an input to the file. Hence open for output means actually for input.
When a file is opened for reading, you will make use of the ifstream as follows :
ifstream.instream("test.txt"); // The file test.txt is opened for reading
When you want to read a file, it means that the file is already present in your directory. Hence if you try to open a file (that isn't present) for reading, what happens?
The answer is, it's an error. When you open a file for writing data, the stream will create the file even if it doesn't exist. But if you attempt to open a file for reading and it isn't present, then it is an error.
Hence you can check whether an error has resulted in the open operation as follows :
if ( ! instream )
{
cout<< "The file cannot be opened";
}
if ( ! instream ) stands for : if not instream (that means if instream not open) then do what is said in the body of the if statement.
In the next section you'll see Writing Text files
or go back to Contents page 2.