您的位置:首页 > 运维架构 > Linux

Linux下的打印当前文件夹下文件的程序

2010-11-16 11:21 477 查看
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>

int list(char* filename)
{
struct stat    statbuf;
struct dirent *dirp;
DIR *dp;
static int depth = 0;
int count = 0;

if (stat(filename, &statbuf) < 0) //得到文件信息
{
puts(filename);
perror("fstat error");
exit(1);
}

if (S_ISDIR(statbuf.st_mode) == 0) //是否是目录
{    //是文件
count++;
for(int i = 0; i < depth; i++)
{
putchar('/t');
}
puts(filename);
}

else
{    //是目录
for(int i = 0; i < depth; i++)
{
putchar('/t');
}
puts(filename);

if((dp = opendir(filename)) == NULL)
{
perror("opendir error");
exit(1);
}

if(chdir(filename) < 0) //更改当前目录为filename
{
perror("fchdir error");
exit(1);
}

depth++;

while ((dirp = readdir(dp)) != NULL) //遍历当前文件夹
{
if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
continue;

strcpy(filename, dirp->d_name);

count += list(filename);
}

if(chdir("..") < 0) //更改当前目录为上一级目录
{
perror("fchdir error");
exit(1);
}
depth--;
}
return count;
}

int main(int argc, char* argv[])
{
char cwd_buff[PATH_MAX];
getcwd(cwd_buff, PATH_MAX);
int n = list(cwd_buff);
printf("total file: %i/n", n);
}


Linux下的打印当前文件夹下文件的程序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: