7

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

我该怎么办?

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

编辑:

我已经下载了 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)){ ...
4

4 回答 4

6

使用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
    }
}
于 2013-08-07T10:02:32.963 回答
3

可以打开存在但包含损坏数据的文件而不会产生不良影响。只要您不尝试读取文件的内容。

但是,任何“检查它是否存在”都受TOCTUI约束,而且一开始就完全没有必要。只是尝试删除文件并接受删除可能并不总是有效是一种更好的方法。

于 2013-08-07T10:09:39.647 回答
2

如果您有任何机会在项目中使用 Boost,则可以使用Boost.Filesystem

#include <boost/filesystem.hpp>

boost::filesystem::path my_file("some/path/some_file");

if (boost::filesystem::exists(my_file))
{
    boost::filesystem::remove(my_file);
}
else
{
    std::cout << "File does not exist!" << std::endl;
}

该解决方案可跨许多系统Boost.Filesystem 实现移植。

于 2013-08-07T10:23:56.857 回答
-3

您想在不尝试打开的情况下做到这一点。如果您改变主意并尝试打开文件:

bool file_exists(std::string filename){
   ifstream ifile(filename);
   return ifile;
}

有人说,这会自动关闭。我不知道。

而且,如果您不想打开文件,我认为有很多机会。我可以说出一个缓慢、老派和丑陋的解决方案,也许其他人会告诉你更好的解决方案。这里是:

system("dir > something.abc");

之后,您必须打开 something.abc 文件,并解析/解释这些行。您必须打开 something.abc 文件,但是,您不必打开您想要分析的那个文件。

这个解决方案会很慢(0.5 秒,这对于 100 个文件来说并不好),你必须编写大量代码,这对于解析/解释“dir”命令的答案将非常复杂。

于 2013-08-07T10:26:15.493 回答