tree命令,将目录文件以树的形式呈现
系统的tree命令效果:
模拟实现tree命令:
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<sys/stat.h>
#include<unistd.h>
void print_tree(const char* dirname, int indent)
{
DIR *pdir = opendir(dirname);
struct dirent *pd;
struct stat sbuf;
chdir(dirname);
while((pd = readdir(pdir)) != NULL)
{
lstat(pd->d_name, &sbuf);
if(strcmp(pd->d_name, ".") == 0 ||
strcmp(pd->d_name, "..") == 0)
{
continue;
}
int depth = indent;
while(depth--)
printf("| _");
printf("%s\n", pd->d_name);
depth = indent;
if(S_ISDIR(sbuf.st_mode))
{
print_tree(pd->d_name, depth+2);
printf("|\n");
}
}
chdir("..");
closedir(pdir);
}
int main(int argc, char* argv[])
{
if(argc != 2)
{
printf("usage: ./tree dir\n");
exit(1);
}
printf("%s\n", argv[1]);
printf("|\n");
print_tree(argv[1], 1);
printf("\n");
return 0;
}
效果:
用到的知识:
DIR结构体
struct __dirstream
{
void *__fd; /* `struct hurd_fd' pointer for descriptor. */
char *__data; /* Directory block. */
int __entry_data; /* Entry number `__data' corresponds to. */
char *__ptr; /* Current pointer into the block. */
int __entry_ptr; /* Entry number `__ptr' corresponds to. */
size_t __allocation; /* Space allocated for the block. */
size_t __size; /* Total valid data in the block. */
__libc_lock_define (, __lock) /* Mutex lock for this structure. */
};
typedef struct __dirstream DIR;
opendir函数 DIR *opendir(const char *name);//打开文件目录
readdir函数 struct dirent *readdir(DIR *dirp);//读取文件目录
closedir函数 int closedir(DIR *dirp);//关闭文件目录
stat结构体
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
dirent结构体
struct dirent
{
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};