2012-02-23 2 views
0

나는 파일 시스템 트리를 탐색하는 C 프로그램을 작성 중이다. 나는 ftw()를 알고 있지만, 내 스스로 그것을하고 싶다. 문제는 내 C 프로그램이 각 노드 (경로/암시 적으로 수행 된)를 각 노드에 대해 수행하지 않고도 각 노드 (디렉토리/파일)를 방문하도록하고 싶습니다.파일 시스템 트리 순회

감사

디렉토리 A가 두 아이 B와 C 각각 B에 도달하는 I 방법이 말과 C는 그에게 C의 내용 및 경로/A/B 및/A와 액세스 B와 C를 읽는 것입니다 /기음. 그러나 여기

+1

여기 정확히 귀하의 질문은 무엇입니까? – noMAD

+0

나는 내 대답이 여기에 있다고 생각한다. http://stackoverflow.com/questions/7035733/unix-c-program-to-list-directories- 재귀 적으로이 행에 "대안으로 디렉토리를 입력 할 때 chdir을 사용할 수있다. 당신이 끝나면 chdir 백업 " –

답변

2

당신은 반복 경로 조회 및 추함을 피할 수 있습니다 (전역 상태 스레드 안전성이 아닌)을 opendir 대신 openatfdopendir을 사용하여 chdir으로 설정합니다.

1

의 참조에서 직접 경로에서와 B와 C에 액세스하고 싶습니다 :

#include <unistd.h> 
#include <stdio.h> 
#include <dirent.h> 
#include <string.h> 
#include <sys/stat.h> 

void printdir(char *dir, int depth) 
{ 
    DIR *dp; 
    struct dirent *entry; 
    struct stat statbuf; 
    int spaces = depth*4; 

    if((dp = opendir(dir)) == NULL) { 
     fprintf(stderr,"cannot open directory: %s\n", dir); 
     return; 
    } 
    chdir(dir); 
    while((entry = readdir(dp)) != NULL) { 
     lstat(entry->d_name,&statbuf); 
     if(S_ISDIR(statbuf.st_mode)) { 
      /* Found a directory, but ignore . and .. */ 
      if(strcmp(".",entry->d_name) == 0 || 
       strcmp("..",entry->d_name) == 0) 
       continue; 
      printf("%*s%s/\n",spaces,"",entry->d_name); 
      /* Recurse at a new indent level */ 
      printdir(entry->d_name,depth+1); 
     } 
     else printf("%*s%s\n",spaces,"",entry->d_name); 
    } 
    chdir(".."); 
    closedir(dp); 
} 

/* Now we move onto the main function. */ 

int main(int argc, char* argv[]) 
{ 
    char *topdir, pwd[2]="."; 
    if (argc != 2) 
     topdir=pwd; 
    else 
     topdir=argv[1]; 

    printf("Directory scan of %s\n",topdir); 
    printdir(topdir,0); 
    printf("done.\n"); 

    return 0; 
} 

Link to the original paper