C ++ operations with file streams: when do I need to check for errors?

Let's say I need to perform several read or write operations on a stream and throw an exception if any of them fail. Is there a difference between two ways:

{
  std::ifstream ifs("filename");
  int i;
  std::string s;
  long l;
  //all variables are local, so I'm not interested in them in case of exception

  //first way
  if(!ifs >> i) throw runtime_error("Bad file");
  if(!std::getline(ifs, s)) throw runtime_error("Bad file");
  if(!ifs >> l) throw runtime_error("Bad file");

  //second way
  ifs >> i;
  std::getline(ifs, s);
  ifs >> l;
  if(!ifs) throw runtime_error("Bad file");

  //do something with variables
}

If there is no difference, then are there any pitfalls in similar cases that I should know?

+4
source share
1 answer

You can enable exceptions:

ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);

In this case, a type exception std::ios_base::failurewill be thrown if the stream cannot read something correctly.

+4
source

Source: https://habr.com/ru/post/1680524/


All Articles