【问题标题】:Check if the file is directory or not检查文件是否是目录
【发布时间】:2015-11-11 05:33:36
【问题描述】:

程序:

#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) 需要检查stat()的返回值是否有错误。 (2) 您在(例如)dir2 上调用stat(),但您需要传递test/dir2
  • 我建议你检查一下stat 返回的内容,我敢打赌大多数名字都是-1(意味着它失败了)。
  • @JoachimPileborg 是的,stat 返回 -1。但是,目录“test”在我当前的工作目录中可用。那么stat如何返回-1。
  • @mohanraj 是的,但那是因为您尝试访问例如文件a 在进程工作目录(您启动程序的目录)中,而不是在test 目录中。仔细阅读 psmears 的评论。

标签: c ls


【解决方案1】:

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

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

  2. 您在目录test 上调用opendir。这实际上是 CWD 中的目录test

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

  4. 第一个条目是.目录,是当前目录的缩写,所有目录都有。

  5. 您用. 调用stat,这意味着您在CWD 上调用stat。它当然成功了,stat 用 CWD 的所有细节填充结构。

  6. 下一次迭代,您将获得 a 条目,并在该条目上调用 stat。但是,由于 CWD 中没有 a,因此 stat 调用失败。但是,您没有对此进行检查,而是使用 previous 调用(来自. 目录的成功stat)填充的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 .

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2014-10-03
    • 2011-05-04
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多