Skip to content

Instantly share code, notes, and snippets.

@martinsbalodis
Created October 10, 2011 15:24
Show Gist options
  • Save martinsbalodis/1275595 to your computer and use it in GitHub Desktop.
Save martinsbalodis/1275595 to your computer and use it in GitHub Desktop.
atrast failu
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
void search_file(char *dir, char *search_filename) {
struct dirent *directory_result;
struct stat st;
// open directory
DIR *directory;
if ((directory = opendir(dir)) == NULL) {
printf("%s isnt a dir!", dir);
exit(-1);
}
char file_location[255];
while ((directory_result = readdir(directory)) != NULL) {
// File location
// = malloc(strlen(dir)+strlen(directory_result->d_name)+1);
strcpy(file_location, dir);
strcat(file_location, directory_result->d_name);
//get file info
stat(file_location, &st);
// file is directory
if(S_ISREG(st.st_mode)) {
// compare file names
if(strcmp(search_filename, directory_result->d_name)==0) {
printf("%s\n", file_location);
}
}
else if(S_ISDIR(st.st_mode) && strcmp(directory_result->d_name,".") !=0 && strcmp(directory_result->d_name,"..") !=0 ) {
// search chld directories
strcat(file_location, "/");
//printf("dir %s\n", file_location);
search_file(file_location, search_filename);
}
}
closedir(directory);
}
/*
*
*/
int main(int argc, char** argv) {
if(argc!=3) {
printf("Missing parameters");
exit(-1);
}
char *dir = argv[1];
char *filename_search = argv[2];
// validate directory
if(dir[strlen(dir)-1]!='/') {
char *dir2 = malloc(strlen(dir)+2);
strcpy(dir2, dir);
strcat(dir2, "/");
dir = dir2;
}
search_file(dir, filename_search);
return (EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment