시스템 호출의 반환 상태, 특히 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
을 찾아야한다 : 당신은 경우 얻을 전화 stat``필요하지 않습니다
#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;
}
"파일"은 디렉토리입니다. 'dirent' 구조체는'DT_DIR' 멤버 인'd_type' 멤버를 가지고 있습니다. –
'print_dir' 호출에서'..' 대신'../'을 시도 했습니까? 이게 효과가 있는지 모르겠지만, 나는 단지 호기심이 많습니다. – maditya
@maditya no ../ 작동하지 않습니다. – swiftk