2016-11-18 28 views
3

我正在使用下面的一段代码来检查文件是否存在或使用std::ifstreamstd :: ifstream初始化文件名​​

#include <iostream> 
#include <fstream> 

int main() 
{ 
    if (std::ifstream("file.txt")) 
    { 
     std::cout << "File present\n"; 
    } 

    return 0; 
} 

因为我没有使用任何std::ifstream对象,我怎么关闭文件?或者不需要致电关闭?

+1

该文件自动关闭(您正在使用*临时*对象)。 – Leon

+0

无关的评论,但不要依赖于这个重要的东西。确保存在文件的唯一方法是打开它并抓住手柄。因为否则另一个程序可能会在您检查后删除文件。 https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use –

回答

2

其实你使用的是无名的临时对象std::ifstream。不需要调用std::ifstream::close(),因为对象在使用后被销毁,并且它的析构函数会正确关闭文件。

为了更精确:

// Temporary object is not yet created here 
if (std::ifstream("file.txt")) 
{ 
    // Temporary object is already destroyed here 
    std::cout << "File present\n"; 
} 
// Or here 

documentation

(析构函数)[虚](隐式地声明)

自毁的basic_ifstream和相关联的缓冲器,关闭文件

1

这是一个临时对象,因此无需关闭它,因为它在完成使用后会自动关闭。 如果您想确保始终可以使用std::ifstream::is_open Here的ifstream中的函数列表