- 帖子
- 7
- 精华
- 0
- 积分
- 79
- 阅读权限
- 20
- 注册时间
- 2013-12-12
- 最后登录
- 2014-1-10
|
长长的c又来了,有点乱没来得急整理。。。- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <dirent.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/stat.h>
- #define PATH_SIZE 4096
- char *path;
- int show_txt(char *);
- int main(int argc, const char *argv[])
- {
- if (argc != 2) {
- printf("Usage: ./a.out <path of dir>\n");
- exit(1);
- }
- path = malloc(PATH_SIZE);
- strcpy(path, argv[1]);
- show_txt(path);
- free(path);
- return 0;
- }
- int show_txt(char *path)
- {
- struct stat statbuf;
- struct dirent *dirp;
- DIR *dp;
- char *ptr;
- int len = strlen(path);
- if (lstat(path, &statbuf) < 0) { /* lstat error */
- perror("lstat error");
- exit(1);
- }
- if (S_ISDIR(statbuf.st_mode) == 0) { /* not a directory */
- if (strcmp(&path[len-4], ".txt") == 0) {
- printf("%s\n", path);
- }
- return 0;
- }
- ptr = path + len;
- *ptr++ = '/';
- *ptr = 0;
- if ((dp = opendir(path)) == NULL) { /* open directory error */
- perror("opendir error");
- exit(1);
- }
- /* iterate the directory(dp)'s each element*/
- while ((dirp = readdir(dp)) != NULL) {
- /* ignore the present directory and the last directory */
- if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
- continue;
- strcpy(ptr, dirp->d_name); /* append the element's name to path */
- show_txt(path); /* call the show_txt(char*) recursively */
- }
- ptr[-1] = 0;
- closedir(dp);
- return 0;
- }
复制代码 |
|