【问题标题】:Listing a directory's content and checking if the element is a file or a directory (C)列出目录的内容并检查元素是文件还是目录 (C)
【发布时间】:2019-08-03 07:15:55
【问题描述】:

我一直在尝试找到一种方法来映射目录的内容以及检查找到的“元素”是文件还是目录。

我已经尝试了这里找到的所有“解决方案”: How can I check if a directory exists?How do you check if a directory exists on Windows in C?Checking if a file is a directory or just a file

(因此,我的帖子不是重复的)

没有什么对我有用。我在 Windows 10 上。无论如何,我不喜欢这些 Windows 库。这就是为什么我正在寻找一种只有标准 C. 到目前为止,这是我的代码:

struct dirent *de;
DIR *dr = opendir(opts->dirname);

#define DF_ISDIR 0x100
#define DF_ISFILE 0x200
#define DF_NOEXIST 0x400


while ((de = readdir(dr)) != NULL) {
    int exists = df_isdirectory(de->d_name);
    printf("[%s]: '%s'\n", exists == DF_ISDIR ? "DIR" : exists == DF_ISFILE ? "FILE" : "WHATEVER", de->d_name);
}

int df_isdirectory(const char *name) {
assert(name != NULL);

DIR *dp = NULL;
if (_access(name, F_OK) == 0) {
    if ((dp = opendir(name)) != NULL) {
        closedir(dp);
        return DF_ISDIR; //  element is directory
    } else {
        return DF_ISFILE; // element is a file
    }
}

return DF_NOEXIST; // element is whatever

}

它给了我以下输出:

如我们所见,程序检测到 .. 和 .作为目录,但不是我目录中的单个元素。即使“another”和“dfgsdgf”是目录!

那么,为什么它不将我的实际目录视为目录? 旁注:一个目录(“dfgsdgf”)是空的,另一个(“another”)是2个文件。

在花了这么多时间并尝试了大量“有效”的解决方案之后,我逐渐厌倦了这一点。我想要一个详细的解释为什么我的代码不能像预期的那样工作以及一个清晰的代码 sn-p 可以 100% 工作。

PS:我的测试目录是 C:\test
我的exe文件不在同一个目录下。

谢谢,祝你有美好的一天! ~塞巴斯蒂安

【问题讨论】:

  • 我不是 Unix 专家,但 dirent 结构有一个 d_type 成员。你检查了吗?
  • @JohnnyMopp 您无需成为 unix 专家即可回答 Windows 问题;)
  • _access(name, F_OK)TOCTOU bug。这样的检查没有任何目的,也不是确定的——access() 有一些方法可以工作,然后opendir() 在实际目录中失败。如果您想知道opendir() 失败的原因,请查看errno

标签: c directory filesystems


【解决方案1】:

在这里,您打开opts 结构中给出的目录:

DIR *dr = opendir(opts->dirname);

opts->dirname 的内容是C:\test。但是,这里:

if ((dp = opendir(name)) != NULL) {

您尝试打开一个目录条目相对于您的 cwd(在其他地方)。事实上,您的_access() 检查已经因此而失败。

尝试调用

chdir(opts->dirname);

在您的 while() 循环之前或在字符串中构建完整路径以将其传递给您的 df_isdirectory() 函数中的 _access()opendir()

【讨论】:

  • 是的,成功了,谢谢!我只是将我的“目录名”附加到 while 循环中找到的文件名并传递修改后的字符串而不是 de->d_name!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 2013-03-15
  • 1970-01-01
  • 2011-12-26
相关资源
最近更新 更多