Do I need to manually close an ifstream?

Do I need to manually call close() when I use a std::ifstream?

For example, in the code:

std::string readContentsOfFile(std::string fileName) {

  std::ifstream file(fileName.c_str());

  if (file.good()) {
      std::stringstream buffer;
      buffer << file.rdbuf();
      file.close();

      return buffer.str();
  }
  throw std::runtime_exception("file not found");
}

Do I need to call file.close() manually? Shouldn’t ifstream make use of RAII for closing files?

5 Answers
5

Leave a Comment