C++ ifstream Error Checking

2019-02-02 05:58发布

问题:

I am new to C++ and want to add error checking to my code plus I want to make sure I'm using good coding practices. I read a line from an ASCII file into a string using:

ifstream paramFile;
string tmp;

//open input file

tmp.clear();

paramFile >> tmp;

//parse tmp
  1. How can I error check to make sure the input file read was successful?

  2. I'm seeing much more complicated ways of reading from an ASCII file out there. Is the way I'm doing it "safe/robust"?

回答1:

paramFile >> tmp; If the line contains spaces, this will not read the whole line. If you want that use std::getline(paramFile, tmp); which reads up until the newline. Basic error checking is done by examining the return values. For example:

if(paramFile>>tmp) // or if(std::getline(paramFile, tmp))
{
    std::cout << "Successful!";
}
else
{
    std::cout << "fail";
}

operator>> and std::getline both return a reference to the stream. The stream evaluates to a boolean value which you can check after the read operation. The above example will only evaluate to true if the read was successful.

Here is an example of how I might make your code:

ifstream paramFile("somefile.txt"); // Use the constructor rather than `open`
if (paramFile) // Verify that the file was open successfully
{
    string tmp; // Construct a string to hold the line
    while(std::getline(paramFile, tmp)) // Read file line by line
    {
         // Read was successful so do something with the line
    }
}
else
{
     cerr << "File could not be opened!\n"; // Report error
     cerr << "Error code: " << strerror(errno); // Get some info as to why
}