UNIX系とBorland C++(dirent.hがあるとはありがたい)でコンパイル可能。VC++の場合は、FindFirstFileとFindNextFileを使わなくちゃいけない。
#include <stdio.h> #include <dirent.h> #include <sys/types.h> void test(char *name){ /* DIR構造体へのポインタを宣言 */ DIR *dirp; /* dirent構造体へのポインタを宣言 */ struct dirent *entp; /* DIR構造体へのポインタを得る(引数はパス) */ dirp = opendir(name); /* dirent構造体へのポインタを得る */ while ((entp = readdir(dirp)) != NULL){ /* ファイル名を出力 */ printf("%s\n", entp->d_name); } closedir(dirp); } int main(int argc, char **argv){ if(argc == 1){ test("."); }else{ test(argv[1]); } return 0; }
file:///usr/include/linux/dirent.h に 構造体direntの宣言 がある。
dirent関数一覧 DIR *opendir(DIR *); int closedir(DIR *); struct dirent *readdir(DIR *); void rewinddir(DIR *); void seekdir(DIR *, off_t); off_t telldir(DIR *); int scandir(const char *, struct dirent ***t, int (*)(const struct dirent *), int (*)(const struct dirent **, const struct dirent **)); int alphasort(const struct dirent **, const struct dirent **); size_t getdirentries(int, char *, size_t, off_t *);
Linuxで、構造体DIRが見つからない……どこだろ。とりあえず、他のプラットフォームでも。
Solaris9付属のdirent.hより、構造体DIRは、こんな感じ。
#if !defined(_POSIX_C_SOURCE) && !defined(_XOPEN_SOURCE) typedef struct { int dd_fd; /* file descriptor */ int dd_loc; /* offset in block */ int dd_size; /* amount of valid data */ char *dd_buf; /* directory block */ } DIR; /* stream data from opendir() */ #else typedef struct { int d_fd; /* file descriptor */ int d_loc; /* offset in block */ int d_size; /* amount of valid data */ char *d_buf; /* directory block */ } DIR; /* stream data from opendir() */ #endif
MinGW付属のdirent.hより、構造体DIRは、こんな感じ。
typedef struct { /* disk transfer area for this dir */ struct _finddata_t dd_dta; /* dirent struct to return from dir */ struct dirent dd_dir; /* _findnext handle */ long dd_handle; /* * Status of search: * 0 = not started yet * (next entry to read is first entry) * -1 = off the end * positive = 0 based index of next entry */ short dd_stat; /* given path for dir with search pattern (struct is extended) */ char dd_name[1]; } DIR;
参考:
- 初心者の初心者による初心者のためのC言語講座 「ls」コマンドを作っちゃおう! (ディレクトリ走査の方法)
- GNU コーディング規約 - 4. あらゆるプログラムの振るまい
- 日経ソフトウエア99年9月号特集1 「ソースコードを読もう!」補足記事
- Manpage of READDIR
- ディレクトリを読む
- 4.3 ディレクトリの検索
- Building and Installing Software Packages for Linux: 3 番目の例: Fortune
- Super ASCII 98年2月号掲載予定だったもの - Linuxプログラミング入門
- ファイルシステムについて(2000年8月9日)
- ディレクトリ(可変長の構造体の入出力)
- 構造体の入力、ディレクトリの構造、リンク
- Defeating Forensic Analysis on Unix
- あるディレクトリ下のファイル一覧の取得方法について
- FindFirstFile()とFindNextFile()でファイルの一覧を取得する
tags: C zurazure
Posted by NI-Lab. (@nilab)