C++ 我需要手动关闭 ifstream 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/748014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:05:00  来源:igfitidea点击:

Do I need to manually close an ifstream?

c++ifstreamraii

提问by Edison Gustavo Muenz

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

close()使用 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 ifstreammake use of RAIIfor closing files?

我需要file.close()手动调用吗?不应该ifstream使用RAII来关闭文件吗?

回答by Eclipse

NO

This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes.

这就是 RAII 的用途,让析构函数完成它的工作。手动关闭它没有坏处,但这不是 C++ 的方式,它是用 C 语言编写的类。

If you want to close the file before the end of a function you can always use a nested scope.

如果您想在函数结束之前关闭文件,您始终可以使用嵌套作用域。

In the standard (27.8.1.5 Class template basic_ifstream), ifstreamis to be implemented with a basic_filebufmember holding the actual file handle. It is held as a member so that when an ifstream object destructs, it also calls the destructor on basic_filebuf. And from the standard (27.8.1.2), that destructor closes the file:

在标准(27.8.1.5 类模板 basic_ifstream)中,ifstream将使用basic_filebuf持有实际文件句柄的成员来实现。它作为一个成员持有,以便当 ifstream 对象析构时,它还调用 上的析构函数basic_filebuf。从标准 (27.8.1.2) 开始,析构函数关闭文件:

virtual ?basic_filebuf();

Effects:Destroys an object of class basic_filebuf<charT,traits>. Calls close().

virtual ?basic_filebuf();

效果:销毁一个类的对象basic_filebuf<charT,traits>。调用close()

回答by Martin York

Do you need to close the file?
NO

你需要关闭文件吗?

Should you close the file?
Depends.

你应该关闭文件吗?
要看。

Do you care about the possible error conditions that could occur if the file fails to close correctly? Remember that close calls setstate(failbit)if it fails. The destructor will call close()for you automatically because of RAIIbut will not leave you a way of testing the fail bit as the object no longer exists.

如果文件未能正确关闭,您是否关心可能发生的错误情况?请记住,setstate(failbit)如果失败,请关闭电话。close()由于RAII析构函数会自动调用您,但不会为您提供测试失败位的方法,因为对象不再存在。

回答by Mark Edwards

I agree with @Martin. If you write to the file, the data may still be sitting on a buffer and may not get written to the file until close()is called. Without doing it manually, you have no idea whether there was an error or not. Not reporting errors to a user is a very bad practice.

我同意@Martin。如果写入文件,数据可能仍位于缓冲区中,并且在close()调用之前可能不会写入文件。如果不手动执行,您不知道是否有错误。不向用户报告错误是一种非常糟糕的做法。

回答by Dimitri C.

No, this is done automatically by the ifstreamdestructor. The only reason you should call it manually, is because the fstreaminstance has a big scope, for example if it is a member variable of a long living class instance.

不,这是由ifstream析构函数自动完成的。您应该手动调用它的唯一原因是因为该fstream实例具有很大的范围,例如,如果它是一个长期存在的类实例的成员变量。

回答by ericcurtin

You can allow the destructor to do it's job. But just like any RAII object there may be times that calling close manually can make a difference. For example:

您可以让析构函数完成它的工作。但就像任何 RAII 对象一样,有时手动调用 close 可能会有所作为。例如:

#include <fstream>

using std::ofstream;

int main() {
  ofstream ofs("hello.txt");
  ofs << "Hello world\n";
  return 0;
}

writes file contents. But:

写入文件内容。但:

#include <stdlib.h>

#include <fstream>

using std::ofstream;

int main() {
  ofstream ofs("hello.txt");
  ofs << "Hello world\n";
  exit(0);
}

doesn't. These are rare cases where a process suddenly exits. A crashing process could do similar.

没有。这些是进程突然退出的罕见情况。崩溃的过程可以做类似的事情。