递归遍历目录下的所有文件,并打印文件名字
2008-10-21 10:26
387 查看
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL) {
fprintf(stderr, "cannot open directory: %s/n", dir);
return;
}
chdir(dir);
while ((entry = readdir(dp)) != NULL) {
//lstat(entry-> d_name,&statbuf);
stat(entry-> d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
/* ignore . and .. */
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
continue;
printf("%*s%s//n", depth, " ", entry->d_name);
printdir(entry-> d_name,depth+4);
} else {
printf("%*s%s/n", depth, " ", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir, pwd[2] =".";
if (argc != 2)
topdir=pwd;
else
topdir=argv[1];
printf("********************Directory scan of %s***********************/n", topdir);
printdir(topdir, 0);
printf("**************************done.********************************/n ");
exit(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL) {
fprintf(stderr, "cannot open directory: %s/n", dir);
return;
}
chdir(dir);
while ((entry = readdir(dp)) != NULL) {
//lstat(entry-> d_name,&statbuf);
stat(entry-> d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
/* ignore . and .. */
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
continue;
printf("%*s%s//n", depth, " ", entry->d_name);
printdir(entry-> d_name,depth+4);
} else {
printf("%*s%s/n", depth, " ", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char* argv[])
{
char *topdir, pwd[2] =".";
if (argc != 2)
topdir=pwd;
else
topdir=argv[1];
printf("********************Directory scan of %s***********************/n", topdir);
printdir(topdir, 0);
printf("**************************done.********************************/n ");
exit(0);
}
相关文章推荐
- java_递归遍历文件目录结构,打印所有的目录名和文件名
- 遍历递归目录下所有文件或文件夹
- Python:递归遍历目录,统计目录大小,并以列表的形式返回所有py文件
- (实用篇)PHP不用递归遍历目录下所有文件的代码
- 面试题-程序题-Java递归实现遍历文件目录(所有文件夹和子文件)
- 在某一磁盘目录下将.txt的所有文件遍历打印到控制台上
- 递归遍历目录中的所有文件
- 使用递归打印该目录下的所有子目录和文件
- PHP遍历并打印指定目录下所有文件实例
- 在某一磁盘目录下将.txt的所有文件遍历打印到控制台上
- VC/MFC 下 递归遍历目录下的所有子目录及文件
- shell编程:递归遍历目录下的所有文件并统一改名
- 递归遍历所有指定目录中的文件及子文件夹中的文件
- MFC递归遍历目录下所有子目录和文件
- Java中如何利用File类递归的遍历指定目录中的所有文件和文件夹
- 用递归遍历一个目录下的所有文件
- 递归遍历目录下所有文件
- C/C++ 遍历linux目录下所有文件并已树的形式打印
- PHP遍历并打印指定目录下所有文件实例
- python - 自定义一个递归函数用于递归遍历指定目录下的所有文件