如何确定父/其他目录中的文件和目录

时间:2013-04-10 23:05:41

标签: c file directory

我发现另一个问题here的答案非常有用。

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;

}

2 个答案:

答案 0 :(得分:2)

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

问题是,当您实际只在the_file中找到时,您正在当前目录中查找文件../the_filereaddir()函数为您提供了相对于其他目录的名称,但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...

答案 1 :(得分:0)

如果您打印出stat,您会发现错误(找不到文件)。

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

所以,假设你有一个文件../test.txt 你在test.txt上调用stat ...那不在目录./test.txt中,但你仍然打印出来自IS_REG的结果。

相关问题