Linux下递归打印一个文件夹下的所有文件夹和文件
2012-03-28 19:51
549 查看
/* We start with the appropriate headers and then a function, printdir,
which prints out the current directory.
It will recurse for subdirectories, using the depth parameter is used for indentation. */
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.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);
if(S_ISDIR(statbuf.st_mode))
{
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
/* Now we move onto the main function. */
int main()
{
printf("Directory scan of /home:\n");
printdir("/home/xchwu/Code",0);
printf("done.\n");
exit(0);
}
which prints out the current directory.
It will recurse for subdirectories, using the depth parameter is used for indentation. */
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.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);
if(S_ISDIR(statbuf.st_mode))
{
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
/* Now we move onto the main function. */
int main()
{
printf("Directory scan of /home:\n");
printdir("/home/xchwu/Code",0);
printf("done.\n");
exit(0);
}
相关文章推荐
- 使用递归打印出一个文件夹下所有子孙文件的树形结构
- Linux递归解压缩一个文件夹下的所有文件
- python程序2(递归查找某一个文件夹下所有的文件是否含有某个特定的字符串,并打印该文件名)
- 学习笔记 - java递归删除一个文件夹及里面的所有文件
- linux下移动文件夹内所有文件到另外一个文件夹下
- 笔试题:递归打印文件夹内所有文件中包含xxx的行
- linux/mac下将一个文件夹中所有文件从当前目录移动到另一目录下
- 递归删除一个文件夹下的所有文件c#代码
- 递归删除一个文件夹下的所有文件c#代码
- 递归遍历一个文件夹下面的所有文件
- 递归 查找 一个文件夹所有的子文件夹和文件
- 每天学点linux--(用shell实现将一个文件夹下面的所有文件拷贝到另一个文件夹下/shell下如何重命名一个文件)
- linux删除同一个文件夹下的所有文件,不包括文件夹
- linux下 c语言递归遍历文件夹下所有文件和子文件夹(附上替换文本文件内容的方法)
- LINUX下查看一个文件夹下所有文件的总大小
- Linux 下统计一个文件夹下所有的文件
- 【理解】一个利用递归打印对象路径下所有文件的小程序
- 在linux中怎样用命令完全拷贝一个目录下的所有文件(包括隐藏文件以及文件夹)到另外一个目录下
- linux命令行下如何以目录树的形式显示一个文件夹的所有文件
- 递归的一些方法使用:深度遍历路径中的所有文件和目录,删除一个有文件的文件夹