Advertisement
DanFloyd

Myfnd

May 12th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.81 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <dirent.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9. #include <time.h>
  10.  
  11. #define N_ARG 3
  12. #define N 128
  13. #define BUF_LIMIT 512
  14.  
  15. #define ec_neg(s,m) \
  16. if( (s) < 0 ) {perror(m); exit(errno);}
  17. #define ec_null(s,m) \
  18. if( (s) == NULL ) {perror(m); exit(errno);}
  19. #define ec_args(s,m) \
  20. if( (s) != N_ARG) {printf(m); usage(); exit(ECANCELED);}
  21. #define ERREAD(s) \
  22. {printf("Couldn't read this directory\n");}
  23.  
  24. static char* s_path;
  25. static int f_flag=0;
  26.  
  27. void usage(){
  28.     printf("Syntax : myfnd dir fname\n");
  29.     printf("Searches into dir the file named fname\n");
  30.     printf("and prints its absolute path and the date\n");
  31.     printf("of its last modification.\n");
  32. }
  33.  
  34. void fnd(char* path, char* name){
  35.    
  36.     DIR* dd;
  37.     struct dirent* ff;
  38.     struct stat fileStat;
  39.     char buf[BUF_LIMIT];
  40.  
  41.     ec_null((getcwd(buf,N)),"Couldn't get the current working directory");
  42.     ec_neg((chdir(path)),"Couldn't change the working directory");
  43.     ec_null((dd=opendir(".")),"Couldn't open this directory");
  44.     while((errno = 0, ff = readdir(dd))!=NULL){
  45.         if(strcmp(ff->d_name,name)==0){
  46.             printf("%s/%s/%s\t\t%s\n",s_path,path,name,(asctime(localtime(&fileStat.st_mtime))));
  47.             f_flag=1;
  48.         }
  49.         ec_neg(stat(ff->d_name,&fileStat),"Couldn't read info for this file\n");
  50.         if(S_ISDIR(fileStat.st_mode)&&(strcmp(ff->d_name,"..")!=0)&&(strcmp(ff->d_name,".")!=0)) fnd(ff->d_name,name);
  51.     }
  52.     if (errno!=0) ERREAD(errno)
  53.     ec_neg((closedir(dd)),"Couldn't close this directory");
  54.     ec_neg((chdir(buf)),"Couldn't return into the previous working directory");
  55. }
  56.  
  57. int main(int argc, char *argv[]){
  58.  
  59.     ec_args(argc,"Wrong arguments number\n");
  60.     s_path = argv[1];
  61.  
  62.     fnd(argv[1],argv[2]);
  63.  
  64.     if(!f_flag) printf("File not found\n");
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement