gpt4 book ai didi

c++ - 你能安全地关闭一个从未打开过的文件吗?

转载 作者:IT老高 更新时间:2023-10-28 23:10:49 35 4
gpt4 key购买 nike

如果我有 std::ofstream可能已打开或未打开,尝试 close 是否安全?换句话说,如果 !is_open()close() 是否会做任何讨厌的事情(抛出异常等)。例如

std::ofstream out;
if (some_condition)
{
out.open(path, std::ios::out);
}

在我处理完文件后,我可以说

out.close();

或者我应该先检查一下

if (out.is_open())
out.close();

std::basic_fstream::close 的唯一描述在 cppreference 上是

Closes the associated file.
Effectively calls rdbuf()->close(). If an error occurs during operation, setstate(failbit) is called.

最佳答案

它完全按照 cppreference 所说的去做:将设置故障位,您可以使用 fail() 方法对其进行检查。例如,以下打印“失败\n”:

#include <iostream>
#include <fstream>
int main(int argc, char ** argv)
{
std::ofstream out;
out.close();
if (out.fail())
std::cout << "fail" << std::endl;
return 0;
}

在与操作系统的交互方面,没有什么可关闭的,但它是无害的。

关于c++ - 你能安全地关闭一个从未打开过的文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33042973/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com