2012-02-23 16 views
0

私はファイルシステムツリーを横断するためのCプログラムを書いています。私はftw()を認識していますが、私自身でそれをやりたいのです。問題は、私のCプログラムが各ノード(ディレクトリ/ファイル)を訪問することなく、各ノードのためにpathlookup(暗黙的に行われたのですが、それも避けたい)しなくてもいいということです。ファイルシステムツリーのトラバーサル

おかげ

は、ディレクトリAは、2人の子供BとCの各Bに到達するためのIの方法を持って言うとCは、彼にCの内容とパス/ A/Bおよび/ AとアクセスBとCを読み取ることです/ C。しかし、ここで

+1

ここにあなたの質問は何ですか? – noMAD

+0

私はここに私の答えを持っていると思うhttp://stackoverflow.com/questions/7035733/unix-c-program-to-list-directories-再帰的にこの行 "あなたはそれらを入力すると、ディレクトリにchdirすることができますあなたが完了したらchdirをバックアップします " –

答えて

2

あなたは繰り返しパスの検索と醜さを避けることができます(グローバルな状態スレッドセーフでない場合)opendirの代わりにopenatfdopendirを使用して、ツリーを走査します。

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

関連する問題