| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

C ディレクトリの走査

提供: MyMemoWiki
2020年2月16日 (日) 04:22時点におけるPiroto (トーク | 投稿記録)による版
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
ナビゲーションに移動 検索に移動

C ディレクトリの走査

directory 関連の関数は header file dirent.h で宣言されており、構造体DIRを使って操作するようになっている。この構造体へのpointer は directory stream(DIR *)と呼ばれ、file stream (FILE *)と同じようなはたらきをする。

opendir

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

readdir

  1. #include <sys/types.h>
  2. #include <dirent.h>
  3. 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を呼び出す必要がある。

telldir

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

seekdir

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

closedir

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

directory走査

  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <dirent.h>
  4. #include <string.h>
  5. #include <sys/stat.h>
  6. void printdir(char *dir, int depth)
  7. { DIR *dp;
  8. struct dirent *entry;
  9. struct stat statbuf;
  10. if ((dp = opendir(dir)) == NULL) {
  11. fprintf(stderr,"cannot open directory: %s\n", dir);
  12. return;
  13. }
  14. chdir(dir);
  15. while((entry = readdir(dp)) != NULL) {
  16. lstat(entry->d_name, &statbuf);
  17. if(S_ISDIR(statbuf.st_mode)) {
  18. if(strcmp(".",entry->d_name) == 0
  19. || strcmp("..",entry->d_name) == 0) {
  20. continue;
  21. }
  22. printf("%*s%s/\n",depth,"",entry->d_name);
  23. printdir(entry->d_name,depth+4);
  24. } else {
  25. printf("%*s%s\n",depth,"",entry->d_name);
  26. }
  27. }
  28. chdir("..");
  29. closedir(dp);
  30. }
  31.  
  32. int main(int argc, char* argv[])
  33. {
  34. if (argc == 2) {
  35. printf("directory scan of %s\n", argv[1]);
  36. printdir(argv[1],0);
  37. printf("done.\n");
  38. }
  39. }

この本からの覚書。