昨日のプログラムに、サブディレクトリのファイルを再帰的にリストアップする -r オプションをつけてみた。
#include #include #include #include #include #include void listfiles(char *path, int recursive); void joinpath(char *path, const char *path1, const char *path2); int main(int argc, char **argv) { char path[256]; char result; int recursive = 0; while ((result = getopt(argc, argv, "r")) != -1) { switch(result) { case 'r': recursive = 1; break; case '?': exit(1); } } if (argc == optind) { strcpy(path, "."); } else { strcpy(path, argv[optind]); } listfiles(path, recursive); return 0; } void listfiles(char *path, int recursive) { DIR *dir; struct dirent *dp; struct stat fi; char path2[256]; dir = opendir(path); for (dp = readdir(dir); dp != NULL; dp = readdir(dir)) { if (dp->d_name[0] != '.') { joinpath(path2, path, dp->d_name); stat(path2, &fi); if (S_ISDIR(fi.st_mode)) { if (recursive) { listfiles(path2, recursive); } } else { printf("%s\n", path2); } } } closedir(dir); return; } void joinpath(char *path, const char *path1, const char *path2) { strcpy(path, path1); strcat(path, "/"); strcat(path, path2); return; }
takatoh@nightschool $ ./listfiles -r . ./stack/linkedlist.c ./stack/linkedlist.h ./stack/main.c ./listfiles ./fib.c ./btreesort.c ./linkedlist.c ./web_color_code.c ./strrand.c ./bmp/win-jpeg.bmp ./bmp/dog2.bmp ./bmp/bmp.c ./bmp/win-4.bmp ./bmp/win-16-1.bmp ./bmp/dog.bmp ./bmp/win-32-bf-888.bmp ./bmp/win-8.bmp ./bmp/win-32.bmp ./bmp/win-16-bf-324.bmp ./bmp/win-32-t.bmp ./bmp/win-16-t.bmp ./bmp/bmp.h ./bmp/os-4.bmp ./bmp/os-1.bmp ./bmp/win-32-bf-td.bmp ./bmp/win-1.bmp ./bmp/win-png.bmp ./bmp/win-8-td.bmp ./bmp/os-8.bmp ./bmp/os-24.bmp ./bmp/win-4-rle.bmp ./bmp/win-16.bmp ./bmp/win-32-bf-833.bmp ./bmp/Makefile ./bmp/win-24.bmp ./bmp/pic1.bmp ./bmp/win-8-rle.bmp ./bmp/bmpinfo.c ./code2rgb.c ./btree/btree.c ./btree/btree.h ./btree/main.c ./mergesort.c ./quicksort.c ./transhex.c ./heapsort.c ./filter.c ./greeting.c ./bubblesort.c ./listfiles.c