0

我发现这里的另一个问题的答案非常有帮助。

sys/stat.h 库似乎有一个限制,因为当我尝试查看其他目录时,所有内容都被视为一个目录。

我想知道是否有人知道另一个系统功能,或者为什么它将当前工作目录之外的任何东西都视为一个目录。

我感谢任何人提供的任何帮助,因为这让我感到困惑,并且各种搜索都没有任何帮助。

我用来测试的代码是:

#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>

int main(void) {

        int status;

        struct stat st_buf;
        struct dirent *dirInfo;

        DIR *selDir;
        selDir = opendir("../");
                                    // ^ or wherever you want to look
        while ((dirInfo = readdir(selDir))) {

                status = stat (dirInfo->d_name, &st_buf);

                if (S_ISREG (st_buf.st_mode)) {
                        printf ("%s is a regular file.\n", dirInfo->d_name);
                }
                if (S_ISDIR (st_buf.st_mode)) {
                        printf ("%s is a directory.\n", dirInfo->d_name);
                }

        }

        return 0;

}
4

2 回答 2

2

您需要检查stat通话状态;它失败了。

问题是你在当前目录中寻找一个文件the_file,而实际上它只存在于../the_file. 该readdir()函数为您提供相对于其他目录的名称,但stat()适用于当前目录。

要使其正常工作,您必须执行以下操作:

char fullname[1024];

snprintf(fullname, sizeof(fullname), "%s/%s", "..", dirInfo->d_name);

if (stat(fullname, &st_buf) == 0)
    ...report on success...
else
    ...report on failure...
于 2013-04-10T23:13:15.820 回答
0

如果您打印出 stat,您会注意到有一个错误(找不到文件)。

这是因为 stat 获取文件的路径,但您只是提供文件名。然后对垃圾值调用 IS_REG。

因此,假设您有一个文件 ../test.txt 您在 test.txt 上调用 stat...它不在目录 ./test.txt 中,但您仍然从 IS_REG 打印出结果。

于 2013-04-10T23:09:17.097 回答