您需要检查系统调用的返回状态,特别是stat()
.
发生的事情是您读取了在..
目录中找到的名称,但是当您调用 时stat()
,您正在这样做./name
而不是../name
.
这段代码应该说明这一点:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
void print_dir(char *dir_n, char *file)
{
DIR *dir = opendir(dir_n);
if (dir == 0)
{
int errnum = errno;
fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum));
exit(1);
}
struct dirent *Dirent;
while ((Dirent = readdir(dir)) != 0)
{
struct stat stats;
if (stat(Dirent->d_name, &stats) < 0)
{
int errnum = errno;
fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", Dirent->d_name, errnum, strerror(errnum));
}
else if (S_ISDIR(stats.st_mode))
{
if (strcmp(file, Dirent->d_name) == 0)
{
printf("found directory %s (inode = %ld)\n", Dirent->d_name, (long)stats.st_ino);
break;
}
else
printf("found directory %s - not a match for %s\n", Dirent->d_name, file);
}
else
{
printf("%s is not a directory\n", Dirent->d_name);
}
}
closedir(dir);
}
int main(void)
{
print_dir("..", "dirtest");
return 0;
}
../dirtest
如果目录存在,这个简单的变体应该找到目录:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
void print_dir(char *dir_n, char *file)
{
DIR *dir = opendir(dir_n);
if (dir == 0)
{
int errnum = errno;
fprintf(stderr, "error: opendir(\"%s\") failed (%d: %s)\n", dir_n, errnum, strerror(errnum));
exit(1);
}
struct dirent *Dirent;
while ((Dirent = readdir(dir)) != 0)
{
char fullname[1024];
snprintf(fullname, sizeof(fullname), "%s/%s", dir_n, Dirent->d_name);
struct stat stats;
if (stat(fullname, &stats) < 0)
{
int errnum = errno;
fprintf(stderr, "error: failed to stat(\"%s\") (%d: %s)\n", fullname, errnum, strerror(errnum));
}
else if (S_ISDIR(stats.st_mode))
{
if (strcmp(file, Dirent->d_name) == 0)
{
printf("found directory %s (%s) (inode = %ld)\n", Dirent->d_name, fullname, (long)stats.st_ino);
break;
}
else
printf("found directory %s - not a match for %s\n", fullname, file);
}
else
{
printf("%s is not a directory\n", fullname);
}
}
closedir(dir);
}
int main(void)
{
print_dir("..", "dirtest");
return 0;
}