Linux下用c语言实现whereis.

简单的一个whereis的实现,代码如下:

 1 #include <stdio.h>
 2 #include <errno.h>
 3 #include <dirent.h>
 4 #include <sys/types.h>
 5 #include <sys/stat.h>
 6 void dir_scan(char *path, char *file, char * fileToSearch);
 7 int count = 0;
 8 
 9 int main(int argc, char *argv[])
10 {
11     struct stat s;
12     if(argc != 3){
13         printf("error argu!");
14         exit(1);
15     }
16     if(lstat(argv[1], &s) < 0){
17         printf("lstat error!");
18         exit(2);
19     }
20     if(!S_ISDIR(s.st_mode)){
21         printf("This is not a dir name!\n");
22         exit(3);
23     }
24     dir_scan("", argv[1], argv[2]);
25     exit(0);
26 }
27 
28 
29 void dir_scan(char * path, char * file, char * fileToSearch)
30 {
31     struct stat s;
32     DIR * dirPtr;
33     struct dirent * dtPtr;
34     char dirName[1000];
35     memset(dirName, 0, 1000 * sizeof(char));
36     strcpy(dirName, path);
37 
38     if(lstat(file, &s) < 0){
39             printf("asdasdad");
40              // fprintf(stdout, "The reason is %s\t ", strerror(errno));
41            exit((4));
42        }
43     if(S_ISDIR(s.st_mode)){
44        strcat(dirName, file);
45        strcat(dirName, "/");
46        // printf("now the dir name is %s\n", file);
47        if((dirPtr = opendir(file)) == NULL){
48             printf("open dir error!\n");
49             exit(5);
50             printf("The count now is %d\n", count);
51        }
52        if(chdir(file) < 0){
53             printf("chdir error!\n");
54             exit(6);
55        }
56        while((dtPtr = readdir(dirPtr)) != NULL){
57             if(dtPtr->d_name[0] == '.')
58                 continue;
59             dir_scan(dirName, dtPtr->d_name, fileToSearch);
60        }
61        if(dirPtr != NULL)
62             closedir(dirPtr);
63        if(chdir("..") < 0){
64             printf("chdir error!\n");
65             exit(7);
66        }
67     }else{
68           if(strstr(file, fileToSearch) != NULL && (!strstr(file, "."))){
69                 printf("%s%s\n", dirName, file);
70                 // printf("adasdadad\n");
71           }
72         count++;
73     }
74 }

 

posted @ 2015-11-01 16:35  eversliver  阅读(493)  评论(0编辑  收藏  举报