Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2969122
  • 博文数量: 272
  • 博客积分: 5544
  • 博客等级: 大校
  • 技术积分: 5496
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 00:48
个人简介

  每个人都要有一个骨灰级的爱好,不为金钱,而纯粹是为了在这个领域享受追寻真理的快乐。

文章分类

全部博文(272)

文章存档

2015年(2)

2014年(5)

2013年(25)

2012年(58)

2011年(182)

分类: LINUX

2013-02-09 12:32:28

#include 
#include 
#include 
#include 
#include 
#include 
#include 


static struct option opts[] = {
    {.name = "help", .has_arg = 0, .val = 'h'},
    {.name = "name", .has_arg = 1, .val = 'n'},
    {.name = "path", .has_arg = 1, .val = 'p'},
    {NULL}
};

static void print_help(void) {
    printf("-h                           Print this help\n");
    printf("-n                           Filename\n");
    printf("-p                           Search path\n");
    exit(-1);
}

static void find_file(char const *name, char const *dir) {
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    char buf[512];
    char path[1024];

    if((dp = opendir(dir)) == NULL) {
        fprintf(stderr,"cannot open directory: %s\n", dir);
        exit(-1);
    }

    chdir(dir);

    while((entry = readdir(dp)) != NULL) {
        lstat(entry->d_name, &statbuf);
        if(S_ISDIR(statbuf.st_mode)) {
            if(strcmp(".", entry->d_name) == 0 || 
		  strcmp("..", entry->d_name) == 0)
			continue;
             find_file(name, entry->d_name);
        } else 
        	if (strcmp(name, entry->d_name) == 0) {
			bzero(buf, 0);
			bzero(path, 0);
			if (getcwd(buf, 512) == NULL) {
				fprintf(stderr, "getcwd failed\n");
				exit(-2);
			}
			snprintf(path, 1024, "%s/%s\n", buf, entry->d_name);
			printf("%s", path);
        	}
    }

    chdir("..");
    closedir(dp);
}


int main(int argc, char **argv) {
	char *name = NULL, *path = NULL;
	char c;

	while((c = getopt_long(argc, argv, "hn:p:d:", opts, NULL)) != -1) {
			switch(c) {
				case 'n':
					name = optarg;
					break;
				case 'p':
					path = optarg;
					break;
				case 'h':
				default:
					print_help();
			}
	}


	find_file(name, path);

	return 0;
}


阅读(2014) | 评论(0) | 转发(0) |
0

上一篇:st_mode判断文件类型

下一篇:sed的模式匹配

给主人留下些什么吧!~~