每个人都要有一个骨灰级的爱好,不为金钱,而纯粹是为了在这个领域享受追寻真理的快乐。
分类: LINUX
2013-02-09 12:32:28
#include#include #include #include #include #include #include static struct option opts[] = { {.name = "help", .has_arg = 0, .val = 'h'}, {.name = "name", .has_arg = 1, .val = 'n'}, {.name = "path", .has_arg = 1, .val = 'p'}, {NULL} }; static void print_help(void) { printf("-h Print this help\n"); printf("-n Filename\n"); printf("-p Search path\n"); exit(-1); } static void find_file(char const *name, char const *dir) { DIR *dp; struct dirent *entry; struct stat statbuf; char buf[512]; char path[1024]; if((dp = opendir(dir)) == NULL) { fprintf(stderr,"cannot open directory: %s\n", dir); exit(-1); } 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; find_file(name, entry->d_name); } else if (strcmp(name, entry->d_name) == 0) { bzero(buf, 0); bzero(path, 0); if (getcwd(buf, 512) == NULL) { fprintf(stderr, "getcwd failed\n"); exit(-2); } snprintf(path, 1024, "%s/%s\n", buf, entry->d_name); printf("%s", path); } } chdir(".."); closedir(dp); } int main(int argc, char **argv) { char *name = NULL, *path = NULL; char c; while((c = getopt_long(argc, argv, "hn:p:d:", opts, NULL)) != -1) { switch(c) { case 'n': name = optarg; break; case 'p': path = optarg; break; case 'h': default: print_help(); } } find_file(name, path); return 0; }