检查文件是否为目录

Check if the file is directory or not

节目:

#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/stat.h>
int main(int argc, char *argv[])
{
    DIR *dp;
    struct dirent *dirp;
    struct stat stbuf;
    if (argc != 2)
        printf("usage: ls directory_name\n");

    if ((dp = opendir(argv[1])) == NULL)
        printf("can’t open %s", argv[1]);

    while ((dirp = readdir(dp)) != NULL){
        stat(dirp->d_name,&stbuf);
        if(S_ISDIR(stbuf.st_mode)){
            printf("Directory: ");
        }
        printf("%s\n",dirp->d_name);
    }

    closedir(dp);
    exit(0);
}

输出:

$ ./a.out test/
dir3
d
c
Directory: .
Directory: a
Directory: ..
Directory: dir4
Directory: dir2
Directory: dir0
Directory: b
Directory: e
Directory: dir1
$

以下是目录 "test" 包含的文件列表。

$ ls -F test/
a  b  c  d  dir0/  dir1/  dir2/  dir3/  dir4/  e
$ 

预期的输出是,如果文件是目录,则输出将是 "Directory: dir1/"。否则只有文件名。 但是,程序的输出并不像预期的那样。程序是否包含任何错误?有没有告诉我一下。

提前致谢...

让我们把它分解成几个步骤:

  1. 您从某个目录启动您的程序。该目录将成为进程当前工作目录(CWD)。

  2. 您在目录 test 上调用 opendir。这个其实就是CWD里面的目录test.

  3. 您调用 readdir 获取目录中的第一个条目。

  4. 第一个入口是.目录,是当前目录的简称,所有目录都有

  5. 您用 . 调用 stat,这意味着您在 CWD 上调用 stat。它当然会成功,并且 stat 用 CWD 的所有详细信息填充结构。

  6. 下一次迭代您将获得条目 a 并在该条目上调用 stat。但是,由于 CWD 中没有 a,因此 stat 调用失败。但是,您不检查它,而是使用从 previous 调用中填充的 stat 结构(来自 [=17 的成功 stat =] 目录).

等等...

您需要告诉 stat 在给定目录而不是 CWD 中查找条目。这基本上只能通过两种方式完成:

  • 格式化一个字符串,以便您在条目前加上您传递给 opendir 的目录。例如

    char path[PATH_MAX];
    snprintf(path, sizeof(path), "%s/%s", argv[1] ,dirp->p_name);
    if (stat(path, &stbuf) != -1)
    {
        // `stat` call succeeded, do something
    }
    
  • 在调用 opendir 之后,但在循环该目录之前,更改 CWD:

    // Opendir call etc...
    
    chdir(argv[1]);
    
    // Loop using readdir etc.
    

或者,从您要检查的目录启动程序:

$ cd test
$ ../a.out .