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

时间:2008-11-06 09:14:52

标签: c++ file file-io

我已经阅读了What's the best way to check if a file exists in C? (cross platform)的答案,但我想知道是否有更好的方法来使用标准的c ++库?最好不要试图打开文件。

stataccess都非常难以辨认。我应该#include使用这些?

10 个答案:

答案 0 :(得分:156)

使用boost::filesystem

#include <boost/filesystem.hpp>

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

答案 1 :(得分:40)

小心竞争条件:如果文件在“存在”检查和打开时间之间消失,程序将意外失败。

最好去打开文件,检查失败,如果一切都好,那么对文件做一些事情。对于安全性至关重要的代码,它更为重要。

有关安全和竞争条件的详细信息: http://www.ibm.com/developerworks/library/l-sprace.html

答案 2 :(得分:29)

我是一个快乐的推动用户,肯定会使用Andreas的解决方案。但如果您无法访问boost库,则可以使用流库:

ifstream file(argv[1]);
if (!file)
{
    // Can't open file
}

它不像boost :: filesystem :: exists那么好,因为文件实际上会被打开...但是那通常是你想要做的下一件事。

答案 3 :(得分:10)

如果跨平台足以满足您的需求,请使用stat()。它不是C ++标准,而是POSIX。

在MS Windows上有_stat,_stat64,_stati64,_wstat,_wstat64,_wstati64。

答案 4 :(得分:9)

access怎么样?

#include <io.h>

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

答案 5 :(得分:8)

另一种可能性是在流中使用good()函数:

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

答案 6 :(得分:7)

我会重新考虑试图找出文件是否存在。相反,您应该尝试以您打算使用它的相同模式打开它(在标准C或C ++中)。知道文件是否存在有什么用处,比如说,当你需要使用它时它是不可写的?

答案 7 :(得分:3)

需要,这将是 overkill

使用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;
}

输出:

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

可以找到另一个版本(和那个)here

答案 8 :(得分:2)

如果您的编译器支持C ++ 17,则无需增强功能,只需使用std::filesystem::exists

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

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

答案 9 :(得分:0)

如果您已经在使用输入文件流类(registration.addUrlPatterns("/run/*/synchronous"); ),则可以使用其功能ifstream

示例:

fail()