如何确定父/其他目录中的文件和目录 [英] How to determine files and directories in parent/other directories

查看:152
本文介绍了如何确定父/其他目录中的文件和目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现此处的其他问题的答案非常有帮助。

I found the answer to another question here to be very helpful.

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

There seems to be a limitation of the sys/stat.h library as when I tried to look in other directories everything was seen as a directory.

我想知道有没有人知道另一个系统功能,或者为什么它看到目前的工作目录之外的任何东西只是一个目录。

I was wondering if anyone knew of another system function or why it sees anything outside the current working directory as only a directory.

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

I appreciate any help anyone has to offer as this is perplexing me and various searches have turned up no help.

我测试的代码是:

#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;

}


推荐答案

检查 stat 调用的状态;它是失败的。

You need to check the status of the stat call; it is failing.

麻烦的是,您正在寻找当前目录中的文件 the_file 实际上只在 ../ the_file 中找到。 readdir()函数给出相对于另一个目录的名称,但 stat()可以将当前目录

The trouble is that you're looking for a file the_file in the current directory when it is actually only found in ../the_file. The readdir() function gives you the name relative to the other directory, but stat() works w.r.t the current directory.

为了使其有效,您必须等同于:

To make it work, you'd have to do the equivalent of:

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...

这篇关于如何确定父/其他目录中的文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆