stat 구조체와 chdir()
글쓴이: zsef123 / 작성시간: 화, 2017/05/23 - 6:47오후
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <dirent.h> #include <sys/stat.h> typedef struct dirent DIRENT; typedef struct dirent* PDIRENT; typedef struct stat STAT; char *target; int dirFilter(PDIRENT entry) { STAT res; stat(entry->d_name, &res); if (S_ISDIR(res.st_mode)) return !(strcmp(entry->d_name, ".")==0 || strcmp(entry->d_name, "..")==0); else return strcmp(target, entry->d_name)==0; } void find(char *path) { PDIRENT *nameList; int fileCount = scandir(path, &nameList, dirFilter, NULL); chdir(path); for(int i=0;i<fileCount;i++) { STAT res; stat(nameList[i]->d_name, &res); if ( S_ISDIR(res.st_mode) ) find(path); else printf("%s/%s\n", path, nameList[i]->d_name); } chdir(".."); } int main(int argc, char **argv) { if(argc == 2) { target=argv[1]; long dirLength = pathconf(".",_PC_PATH_MAX ); char *curPath = malloc(sizeof(char)*dirLength); getcwd(curPath,dirLength); find(curPath); } else if (argc > 2) { target=argv[2]; find(argv[1]); } return 0;
경로와 파일이름을 입력받아 해당 경로에서 파일을 찾는 코드를 구현하고 싶습니다
main.o /bin ls 를 입력 했을 때 /bin/ls와 함께 /bin/fgetty-login2가 같이 나와서 디버깅을 해보니
fgetty-login2 파일에 대해 dirFilter 함수에서의 st_mode 값과 find 함수에서 st_mode 값이 달라서
dirFilter에선 fgetty_login2가 디렉토리로, find 함수에선 파일로 나와 문제가 생겼습니다.
find함수 내에서 scandir과 chdir 함수의 실행 순서를 바꿔보니
원하던 결과가 나오는데 왜 이렇게 되는지 궁금합니다
Forums:
stat 의 반환값을 확인하세요. 에러리턴인지
stat 의 반환값을 확인하세요. 에러리턴인지 아닌지.
댓글 달기