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 }

 

转载于:https://www.cnblogs.com/-wang-cheng/p/4928098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值