我已经阅读了什么是检查C中是否存在文件的最佳方法的答案?(跨平台),但我想知道是否有更好的方法来使用标准的c ++库?最好不要试图打开文件.
这两个stat和access是几乎ungoogleable.我#include该怎么用?
And*_*son 159
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
rle*_*lut 41
注意竞争条件:如果文件在"存在"检查和打开时间之间消失,程序将意外失败.
最好去打开文件,检查失败,如果一切都好,那么对文件做一些事情.对于安全性至关重要的代码,它更为重要.
有关安全性和竞争条件的详细信息:http: //www.ibm.com/developerworks/library/l-sprace.html
Mat*_*tyT 30
我是一个快乐的推动用户,肯定会使用Andreas的解决方案.但是,如果您无法访问boost库,则可以使用流库:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
Run Code Online (Sandbox Code Playgroud)
它不像boost :: filesystem :: exists那么好,因为文件实际上会被打开...但是那通常是你想要做的下一件事.
act*_*.se 11
如果跨平台足以满足您的需求,请使用stat().它不是C++标准,而是POSIX.
在MS Windows上有_stat,_stat64,_stati64,_wstat,_wstat64,_wstati64.
怎么样access?
#include <io.h>
if (_access(filename, 0) == -1)
{
// File does not exist
}
Run Code Online (Sandbox Code Playgroud)
另一种可能性good()是在流中使用该函数:
#include <fstream>
bool checkExistence(const char* filename)
{
ifstream Infield(filename);
return Infield.good();
}
Run Code Online (Sandbox Code Playgroud)
如果你的编译器支持 C++17 你不需要 boost,你可以简单地使用 std::filesystem::exists
#include <iostream> // only for std::cout
#include <filesystem>
if (!std::filesystem::exists("myfile.txt"))
{
std::cout << "File not found!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)