可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
Both stat
and access
are pretty much ungoogleable. What should I #include
to use these?
回答1:
Use boost::filesystem:
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
回答2:
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
回答3:
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:
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.
回答4:
Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.
On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.
回答5:
How about access
?
#include <io.h>
if (_access(filename, 0) == -1)
{
// File does not exist
}
回答6:
Another possibility consists in using the good()
function in the stream:
#include <fstream>
bool checkExistence(const char* filename)
{
ifstream Infield(filename);
return Infield.good();
}
回答7:
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?
回答8:
NO boost REQUIRED, which would be an overkill.
Use stat() (not cross platform though as mentioned by pavon), like this:
#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.
回答9:
If you are already using the input file stream class (ifstream
), you could use its function fail()
.
Example:
ifstream myFile;
myFile.open("file.txt");
// Check for errors
if (myFile.fail()) {
cerr << "Error: File could not be found";
exit(1);
}