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

linux系统调用之文件:递归实现tree命令

2009-11-22 20:26 911 查看
Code:

/*打�目录下所有文件的大�*/

#include <sys/types.h>

#include <dirent.h>

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <unistd.h>

#include <string.h>

#define BUF_LEN 1024

//int stat(const char *path, struct stat *buf);

//int fstat(int filedes, struct stat *buf);

//int lstat(const char *path, struct stat *buf);



//DIR *opendir(const char *name);

//struct dirent *readdir(DIR *dir);



void check_mode(struct stat *st, char mode[])

{

if(S_ISREG(st->st_mode)) mode[0] = '-';

else if(S_ISDIR(st->st_mode)) mode[0] = 'd';

else if(S_ISCHR(st->st_mode)) mode[0] = 'c';

else if(S_ISBLK(st->st_mode)) mode[0] = 'b';

else if(S_ISFIFO(st->st_mode)) mode[0] = 'f';

else if(S_ISLNK(st->st_mode)) mode[0] = 'l';

else if(S_ISSOCK(st->st_mode)) mode[0] = 's';



if(S_IRUSR & st->st_mode) mode[1] = 'r';

else mode[1] = '-';

if(S_IWUSR & st->st_mode) mode[2] = 'w';

else mode[2] = '-';

if(S_IXUSR & st->st_mode) mode[3] = 'x';

else mode[3] = '-';

if(S_IRGRP & st->st_mode) mode[4] = 'r';

else mode[4] = '-';

if(S_IWGRP & st->st_mode) mode[5] = 'w';

else mode[5] = '-';

if(S_IXGRP & st->st_mode) mode[6] = 'x';

else mode[6] = '-';

if(S_IROTH & st->st_mode) mode[7] = 'r';

else mode[7] = '-';

if(S_IWOTH & st->st_mode) mode[8] = 'w';

else mode[8] = '-';

if(S_IXOTH & st->st_mode) mode[9] = 'x';

else mode[9] = '-';

}



void ls(char *name, char argv)

{

char buf[BUF_LEN];

struct dirent *read_dir, *read_last = NULL;

struct stat st;

DIR *dir;

char mode[10];

static int deep = 0;

int i;



if((dir = opendir(name)) == NULL)

{

fprintf(stderr, "Can not open %s/n", name);

exit(1);

}



while((read_dir = readdir(dir)) != NULL)

{

strcpy(buf, name);

strcat(buf, "/");

strcat(buf, read_dir->d_name);



if(stat(buf, &st) < 0)

{

fprintf(stderr, "Stat Error/n");

exit(0);

}

// check_mode(&st, mode);

// printf("%s %s %d/n",mode, read_dir->d_name, st.st_size);



if(read_last != NULL)

{

putchar('|');

for(i = 0; i < deep; i++)

{

printf(" |");

}

printf("-- %s/n", read_last->d_name);

}

read_last = read_dir;

if(S_ISDIR(st.st_mode) && argv == 'R'

&& strcmp(read_dir->d_name, ".") != 0

&& strcmp(read_dir->d_name, "..") != 0 && !S_ISLNK(st.st_mode))

{

deep++;

ls(buf, argv);

deep--;

}

}



if(deep > 0) putchar('|');

else putchar('`');



for(i = 0; i < deep - 1; i++)

{

printf(" |");

}

if(deep > 0)

{

printf(" `");

}

printf("-- %s/n", read_last->d_name);

}



int main(int argc, char **argv)

{

char *name;



if(argc > 3)

{

fprintf(stderr, "Usage <%s><dirname>[-R]/n", argv[0]);

exit(1);

}

else if(argc > 1)

{

name = argv[1];

}

else

{

name = ".";

}



putchar('/n');

printf("%s/n", argv[1]);

if(argc < 3) ls(name, 0);

else ls(name, argv[2][1]);



putchar('/n');

return 0;



}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: