#include #include #include #include #include #include #include /* search for filename in the dirname directory */ void find_file(const char*filename, const char* dirname) { #if DEBUG printf("Searching for file %s in directory %s\n", filename, dirname); #endif DIR* dir = opendir(dirname); if(dir == NULL) { fprintf(stderr, "cannot open directory %s\n", dir); return ; } struct dirent* cur_dirent = readdir(dir); /* browse the entries in the directory */ while(cur_dirent != NULL) { if(strcmp(cur_dirent->d_name, filename) == 0) { printf("Found %s/%s\n", dirname, filename); } if(strcmp(".", cur_dirent->d_name) != 0 && strcmp("..", cur_dirent->d_name) != 0) { char pathname[1024]; sprintf(pathname, "%s/%s", dirname, cur_dirent->d_name); struct stat s; int ret = stat(pathname, &s); assert(ret == 0); if(S_ISDIR(s.st_mode)) { /* pathname is a directory. call find_file recursively */ find_file(filename, pathname); } } /* get the next entry */ cur_dirent = readdir(dir); } } int main(int argc, char**argv) { if(argc != 3) { fprintf(stderr, "Usage: %s file dirname\n", argv[0]); return EXIT_FAILURE; } char* filename = argv[1]; char* dirname = argv[2]; find_file(filename, dirname); return EXIT_SUCCESS; }