检查 C++ 中文件是否存在的最佳方法是什么?(跨平台)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/268023/
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
What’s the best way to check if a file exists in C++? (cross platform)
提问by c0m4
I have read the answers for What's the best way to check if a file exists in C? (cross platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all.
我已阅读检查文件是否存在于 C 中的最佳方法是什么的答案?(cross platform),但我想知道是否有更好的方法使用标准 C++ 库来做到这一点?最好不要尝试打开文件。
Both stat
and access
are pretty much ungoogleable. What should I #include
to use these?
这两个stat
和access
是几乎ungoogleable。我应该怎么#include
用这些?
回答by Andreas Magnusson
Use boost::filesystem:
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
回答by rlerallut
Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.
注意竞争条件:如果文件在“存在”检查和您打开它之间消失,您的程序将意外失败。
It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.
最好去打开文件,检查是否失败,如果一切正常,然后对文件做一些事情。对于安全关键代码,这一点更为重要。
Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html
有关安全性和竞争条件的详细信息:http: //www.ibm.com/developerworks/library/l-sprace.html
回答by MattyT
I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:
我是一个快乐的 boost 用户,肯定会使用 Andreas 的解决方案。但是,如果您无权访问 boost 库,则可以使用流库:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.
它不如 boost::filesystem::exists 好,因为文件实际上会被打开……但这通常是你接下来要做的事情。
回答by activout.se
Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.
使用 stat(),如果它足够跨平台满足您的需求。不过,它不是 C++ 标准,而是 POSIX。
On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.
在 MS Windows 上有 _stat、_stat64、_stati64、_wstat、_wstat64、_wstati64。
回答by Rob
How about access
?
怎么样access
?
#include <io.h>
if (_access(filename, 0) == -1)
{
// File does not exist
}
回答by Samer
Another possibility consists in using the good()
function in the stream:
另一种可能性good()
是在流中使用该函数:
#include <fstream>
bool checkExistence(const char* filename)
{
ifstream Infield(filename);
return Infield.good();
}
回答by fizzer
I would reconsider trying to find out if a file exists. Instead, you should try to open it (in Standard C or C++) in the same mode you intend to use it. What use is knowing that the file exists if, say, it isn't writable when you need to use it?
我会重新考虑尝试找出文件是否存在。相反,您应该尝试以您打算使用它的相同模式打开它(在标准 C 或 C++ 中)。知道文件存在有什么用,比如说,当你需要使用它时它不可写?
回答by AlbertM
If your compiler supports C++17 you don't need boost, you can simply use std::filesystem::exists
如果你的编译器支持 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;
}
回答by gsamaras
NO boostREQUIRED, which would be an overkill.
NO提振REQUIRED,这将是一个矫枉过正。
Use stat()(not cross platform though as mentioned by pavon), like this:
使用stat()(尽管 pavon 提到的不是跨平台),如下所示:
#include <sys/stat.h>
#include <iostream>
// true if file exists
bool fileExists(const std::string& file) {
struct stat buf;
return (stat(file.c_str(), &buf) == 0);
}
int main() {
if(!fileExists("test.txt")) {
std::cerr << "test.txt doesn't exist, exiting...\n";
return -1;
}
return 0;
}
Output:
输出:
C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt
ls: test.txt: No such file or directory
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
test.txt doesn't exist, exiting...
Another version (and that) can be found here.
另一个版本(和那个)可以在这里找到。
回答by Reza Saadati
If you are already using the input file stream class (ifstream
), you could use its function fail()
.
如果您已经在使用输入文件流类 ( ifstream
),则可以使用其函数fail()
。
Example:
例子:
ifstream myFile;
myFile.open("file.txt");
// Check for errors
if (myFile.fail()) {
cerr << "Error: File could not be found";
exit(1);
}