gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:36 25 4
gpt4 key购买 nike

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

我该怎么做?

(只需删除并接受错误即可,但我这样做是为了学习,所以我想正确地做...)

编辑:

我已经下载了 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

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

boost::filesystem::path my_file(s4);
if (boost::filesystem::exists(my_file)){ ...

最佳答案

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

关于c++ - 检查文件是否存在而不打开它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18100391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com