检查文件是否存在而不打开它

Sam*_*Sam 5 c++ macos error-handling file delete-file

在继续我的程序之前,如何检查目录中是否存在文件?我已经阅读了尝试使用各种方法打开文件的答案,但我的问题是,大多数情况下,我正在检查的文件将损坏并且无法打开.这发生在我的程序的错误检查部分,只有在前面的代码中发生错误时才会触发.我想检查文件是否存在,如果是,则要求删除它,否则只打印一些消息.

我怎么能这样做?

(只是删除并接受错误会起作用,但我这样做是为了学习,所以我想要正确地做...)

编辑:

我已经下载了Boost来使用文件系统库并编译它,看似没有错误,但是当我尝试编译我的程序时,我得到了这个响应:

g++ program.cpp -I <path to>/boost_1_54_0 -o output

Undefined symbols for architecture x86_64:
"boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code*)", referenced from:
  boost::filesystem::exists(boost::filesystem::path const&)in cc1XX8rD.o
"boost::system::system_category()", referenced from:
  __static_initialization_and_destruction_0(int, int)in cc1XX8rD.o
"boost::system::generic_category()", referenced from:
  __static_initialization_and_destruction_0(int, int)in cc1XX8rD.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我在程序中使用boost的唯一地方是:

boost::filesystem::path my_file(s4);
if (boost::filesystem::exists(my_file)){ ...
Run Code Online (Sandbox Code Playgroud)

Dav*_* Xu 5

使用stat()access()

#include <unistd.h>

int res = access(path, R_OK);
if (res < 0) {
    if (errno == ENOENT) {
         // file does not exist
    } else if (errno == EACCES) {
         // file exists but is not readable
    } else {
         // FAIL
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如何链接到[原始答案](http://stackoverflow.com/a/8580721/1438393)? (3认同)