トップ 一覧 ping 検索 ヘルプ RSS ログイン

C ディレクトリの走査の変更点

  • 追加された行はこのように表示されます。
  • 削除された行はこのように表示されます。
!!!C ディレクトリの走査
directory 関連の関数は header file dirent.h で宣言されており、構造体DIRを使って操作するようになっている。この構造体へのpointer は directory stream(DIR *)と呼ばれ、file stream (FILE *)と同じようなはたらきをする。

!!opendir
 #include <sys/types.h>
 #include <dirent.h>
 DIR *opendir(const char *name);
*directory を open し、direcotry stream を確立する。
*失敗すると、null pointer を返す。

!!readdir
 #include <sys/types.h>
 #include <dirent.h>
 DIR *readdir(DIR *dirp);
*dirp で指定された directory stream の中の次の directory entry を示す構造体へのpointer を返す。
*以後、呼び出されるたびに、次のdirectory entry を返す。
*dirent構造体には、以下の要素が含まれている。
**ino_t d_ino fileのi-node
**char d_name[] fileの名前
*詳しい情報が必要な場合、[[stat|C 低水準ファイルアクセス]]を呼び出す必要がある。

!!telldir
 #include <sys/types.h>
 #include <dirent.h>
 long int telldir(DIR *dirp);
*directory stream 中の現在の位置を記録している値を返す。
*この値を使ってseekdirを呼び出せば、directory の走査を現在位置に再設定できる。

!!seekdir
 #include <sys/types.h>
 #include <dirent.h>
 void seekdir(DIR *dirp, long int loc);
*dirpで指定されたdirectory stream 中のdirectory entry pointer を設定。
*位置の指定に使うlocの値は、事前にtelldirで取得しておく。

!!closedir
 #include <sys/types.h>
 #include <dirent.h>
 int closedir(DIR *dirp);
*directory stream を close し関連付けられていたresourceを開放する。
*成功すると 0を返し、失敗すると -1を返す。


!!directory走査
 #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;
   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)) {
       if(strcmp(".",entry->d_name) == 0
         || strcmp("..",entry->d_name) == 0) {
         continue;
       }
       printf("%*s%s/\n",depth,"",entry->d_name);
       printdir(entry->d_name,depth+4);
     } else {
       printf("%*s%s\n",depth,"",entry->d_name);
     }
   }
   chdir("..");
   closedir(dp);
 }
 
 int main(int argc, char* argv[])
 {
   if (argc == 2) {
     printf("directory scan of %s\n", argv[1]);
     printdir(argv[1],0);
     printf("done.\n");
   }
 }      

----
この本からの覚書。
{{amazon 4797327014}}