【发布时间】: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 的评论。