Chinaunix首页 | 论坛 | 博客
  • 博客访问: 145766
  • 博文数量: 37
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 125
  • 用 户 组: 普通用户
  • 注册时间: 2015-09-28 11:52
个人简介

回首向来萧瑟处,也无风雨也无晴

文章存档

2016年(1)

2015年(36)

我的朋友

分类: Android平台

2015-12-16 09:59:56

在adb中经常需要查找一些文件或者是目录,但是很可惜adb所用busybox指令集中并没有包含find命令;
所以在多次觉得不便胡情况下,决定自己用C 语言实现一个find命令的精简版本,仅仅为了查找文件或者目录;
代码如下:
find.c:
#include
#include
#include
#include
#include
#include
#include
#include"unistd.h"
#include"sys/types.h"
#include"fcntl.h"

int findfile(char *filename,char *path){
    struct stat statbuf;
    struct dirent *dirp;
    DIR *dp;
    char tmpbuf[100];
    char *ptr;
    int num;
    if(lstat(path,&statbuf) < 0){
        fprintf(stderr,"lstat is error %s",strerror(errno));
        return 0;
    }
    if(S_ISDIR(statbuf.st_mode) == 0){ //is a dir
        return 0;
    }    
    if((dp = opendir(path)) == NULL){
        fprintf(stderr,"opendir is error %s \n",strerror(errno));
        return 0;
    }
    ptr = path + strlen(path);
    *ptr++ = '/';
    *ptr = 0;
    while((dirp = readdir(dp)) != NULL){
        num = 0;
        if(strcmp(dirp->d_name,".") == 0 || strcmp(dirp->d_name,"..") == 0)
            continue;
        strcpy(ptr,dirp->d_name);
        if(strcmp(dirp->d_name,filename) ==0){
            printf("the result:%s\n",path);
        }        
        if(findfile(filename,path) != 0)       //使用递归层级查找所有当前目录下以及当前目录下胡目录下存在的同名文件
           break;
    }
    closedir(dp);
    return 0;
}

int main(int arg,char **argc)
{
    int i=0;
int ret;
// int resend;
char *tmppath,*path;
char *filename;
FILE *fp;
 
// printf("111111111111111111111\n");
// for(i = 0; i < arg; i++ )
// printf("the %d argc is %s\n",i,argc[i]);
    if(arg != 3){
        fprintf(stderr,"args lack:%s\n",strerror(errno));
        return -1;
    }else{
    printf("the original path is %s\n",argc[1]);
    path = realpath(argc[1],tmppath);
     printf("the path: %s\n",path);
     filename = argc[2];
     printf("to find filename : %s\n",argc[2]);
    }   
    printf("start:\n\n");

    ret = findfile(filename,path);
    printf("over!\n\n");
    exit(ret);
}
程序写完之后,利用交叉编译工具,将find.c编译成android下能运行的可执行程序:
我所用的是交叉编译工具是arm-none-linux-gnueabi-gcc  4.4.3版本的;
配置交叉编译工具环境变量就不多说了:
编译find.c文件成find可执行文件
lei_lei.zhou@bj61019pcu:~/Find$ arm-none-linux-gnueabi-gcc find.c -static -o find   
将find文件push到adb中去:
lei_lei.zhou@bj61019pcu:~/Find$ adb push find /system/bin/
(如果出现failed to copy 'find' to '/system/bin//find': Read-only file system错误,进入到adb shell中执行mount -o rw,remount /system将system文件夹变为可读写的文件系统,再执行上一个命令)
find文件push到system中去了,就可以直接用find查找文件了;
注意这个find命令仅仅实现一个简单且常用查找方式方法:
用法:find <查找起始路径> <想要查找的文件>
例如:
lei_lei.zhou@bj61019pcu:~/Find$ adb shell
root@MyTestPhone:/ # find ./ wipe                        //在当前根目录向下搜索wipe文件,结果在/system/bin下存在
the path: /
to find filename : wipe
start:

the result://system/bin/wipe
over!

至此,find命令移植到android中完成,如有什么问题可直接联系我:
qq:996340566  





阅读(4827) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~