功能很简单,列出当前给定目录"MyDirectory"里的文件和文件夹,就第一层深度。
用gdb看了下,有些st_mode为0,请问为什么呢?
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
int main(void)
{
DIR *pDir = opendir("MyDirectory");
struct dirent *pDirent;
struct stat vStat;
if (pDir == NULL)
{
printf("Can't open the directory \"MyDirectory\"");
exit(1);
}
while ((pDirent = readdir(pDir)) != NULL)
{
stat(pDirent->d_name, &vStat);
if (S_ISDIR(vStat.st_mode))
printf("Directory: %s\n", pDirent->d_name);
else
printf("File: %s\n", pDirent->d_name);
}
closedir(pDir);
return 0;
}
答案在于stat调用失败!根据返回的errno表示没有这个文件或文件夹。
因为目前还是在当前目录,而不是在"MyDirectory"下。所以文件路径pathname就不存在。
解决方法有二:
一是在将MyDictory的名字也加进来:
char *directory = "MyDirectory";
size_t directory_length = strlen(directory);
char *path = malloc(directory_length + 1 + NAME_MAX);
strcpy(path, directory);
path[directory_length] = '/';
while ((pDirent = readdir(pDir)) != NULL) {
strcpy(path + directory_length + 1, pDirent->d_name);
if (stat(path, &vStat) == -1) {
perror(path);
continue;
}
…
}
二是进入该目录:
chdir("MyDictory");
man 2 stat, 搜st_mode
S_ISDIR http://bbs.chinaunix.net/thread-628868-1-1.html
PS:APUE里面居然讲过这些,一点印象都没有,貌似从来都没需求判断目录之类的。