检查文件是否存在于 C + + 中的最好方法是什么? (跨平台)

我已经阅读了 检查文件是否存在于 C 语言中的最好方法是什么? (跨平台)的答案,但是我想知道是否有更好的方法来使用标准的 c + + 库实现这一点?最好不要试图打开文件。

stataccess都很难用谷歌搜索。我应该怎样使用 #include呢?

119089 次浏览

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.

Use boost::filesystem:

#include <boost/filesystem.hpp>


if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}

How about access?

#include <io.h>


if (_access(filename, 0) == -1)
{
// File does not exist
}

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?

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.

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

Another possibility consists in using the good() function in the stream:

#include <fstream>
bool checkExistence(const char* filename)
{
ifstream Infield(filename);
return Infield.good();
}

NO 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.

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);
}

If your compiler supports C++17 you don't need boost, you can simply use std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>


if (!std::filesystem::exists("myfile.txt"))
{
std::cout << "File not found!" << std::endl;
}