在看Nginx代码的时候,经常需要在代码文件中查找一些特定的字符串,觉得系统本身自带的grep输出
格式太丑陋了,又不想去学习那么多繁琐的命令参数,干脆自己实现了一个,感觉还挺好用的。
- #include <apue.h>
- #define end(s) ((char *) (s) + strlen(s))
- typedef void (*file_handler)(const char *path, void *args);
- char content[128];
- int main(int argc, char **argv)
- {
- int len;
- char path[1024], *p;
- assert(argc == 3);
- if (chdir(argv[1]))
- err_sys("chdir error");
- if (getcwd(path, sizeof path) == NULL)
- err_sys("getcwd error");
- p = argv[2];
- len = strlen(p);
- if (len > 2 && *p == '"' && p[len - 1] == '"')
- strncpy(content, p + 1, len - 2);
- else
- strncpy(content, p, len);
- printf("\nSearch directory : %s for string \"%s\"\n", path, content);
- dir_walk(path, grep_file, content);
- printf("\n");
- return 0;
- }
- void
- dir_walk(const char *dname, file_handler handler, void *args)
- {
- DIR *dp;
- struct stat statbuf;
- struct dirent *dirp;
- char fullpath[1024];
- if ((dp = opendir(dname)) == NULL)
- err_sys("opendir %s error", dname);
- while ((dirp = readdir(dp)) != NULL) {
- if (!strcmp(dirp->d_name, ".") ||
- !strcmp(dirp->d_name, ".."))
- continue;
- snprintf(fullpath, sizeof fullpath, "%s/%s", dname, dirp->d_name);
-
- if (lstat(fullpath, &statbuf) < 0)
- err_sys("lstat error");
-
- if (S_ISDIR(statbuf.st_mode))
- dir_walk(fullpath, handler, args);
- else
- handler(fullpath, args);
- }
- closedir(dp);
- }
- static void
- grep_file(const char *path, void *data)
- {
- int fd, nline;
- FILE *fp;
- char *p, *content;
- char line[1024];
- static int count;
- content = (char *) data;
- if ((fd = open(path, O_RDONLY)) < 0)
- err_sys("file %s open error", path);
-
- if ((fp = fdopen(fd, "r")) == NULL)
- err_sys("fdopen %s error", path);
- nline = 0;
- while (fgets(line, sizeof line, fp)) {
-
- nline++;
- if ((p = strstr(line, content)))
- printf("\n%d . %s : %d\n\t%s", ++count, path, nline, line);
- }
- fclose(fp);
- close(fd);
- }
阅读(2413) | 评论(0) | 转发(0) |