、递归打印文件夹
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
void printDir(char *dirname) {
char pathname[1024];
DIR *dir;
struct dirent *dp;
struct stat st;
if(!(dir=opendir(dirname))) {//打开一个目录
perror("opendir");
exit(1);
}
while(dp = readdir(dir)) {
if(!strcmp(dp->d_name, ".") || !strcmp(dp->d_name,"..")) continue;
sprintf(pathname, "%s/%s", dirname, dp->d_name);//拼接,获得当前文件路径
if(stat(pathname, &st) < 0) {
perror("stat");
exit(1);
}
if(S_ISDIR(st.st_mode)) {//判断是否是文件夹
printDir(pathname);
}
printf("%s\t", dp->d_name);//打印目录下下的文件名
}
putchar(10);//换行
closedir(dir);
}
int main(int argc, char **argv) {
if(argc < 2) {
printf("usage:cmd + filename\n");
return 1;
}
printDir(argv[1]);
return 0;
}
仔细观察,可以发现,文件确实一层一层的打印出来了;
3、实现ls
- 相关函数的使用,可以将光标移动到该函数,然后在命令模式键盘下输入K即可查看
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<pwd.h>
#include<grp.h>
#include<time.h>
void ls_al(char *path) {
if (chdir(path) < 0) {
perror("path");
}
DIR *dir = opendir(".");//当前路径
struct dirent *dir_info ;
struct stat info_buf;
char file_type = '-';//记录文件类型
char power[10] = "---------";//权限的字符数组
while(dir_info = readdir(dir)) {
if(stat(dir_info->d_name , &info_buf) < 0) {
perror("stat");
exit(1);
}
switch(info_buf.st_mode & S_IFMT) {
case S_IFSOCK:
file_type = 's';
break;
case S_IFLNK:
file_type = 'l';
break;
case S_IFREG:
file_type = '-';
break;
case S_IFBLK:
file_type = 'b';
break;
case S_IFDIR:
file_type = 'd';
break;
case S_IFCHR:
file_type = 'c';
break;
case S_IFIFO:
file_type = 'p';
break;
default:
break;
}
power[0] = info_buf.st_mode & S_IRUSR ?'r':'-';
power[1] = info_buf.st_mode & S_IWUSR ?'w':'-';
power[2] = info_buf.st_mode & S_IXUSR ?'x':'-';
power[3] = info_buf.st_mode & S_IRGRP ?'r':'-';
power[4] = info_buf.st_mode & S_IRGRP ?'w':'-';
power[5] = info_buf.st_mode & S_IRGRP ?'x':'-';
power[6] = info_buf.st_mode & S_IROTH ?'r':'-';
power[7] = info_buf.st_mode & S_IROTH ?'w':'-';
power[8] = info_buf.st_mode & S_IROTH ?'x':'-';
struct passwd *pwd = getpwuid(info_buf.st_uid);//用户信息
struct group *grp = getgrgid(info_buf.st_gid);//组信息
struct tm *mtime = localtime(&info_buf.st_mtime);//当前时间
printf("%c%s %3d %s %s %8d %4d-%02d-%02d %2d:%02d:%02d %s\n",
file_type,//文件类型
power , //权限
info_buf.st_nlink,//硬链接
pwd->pw_name,//用户名
grp->gr_name,//所属组名
info_buf.st_size,//文件大小
//info_buf.st_mtime,
mtime->tm_year + 1900,
mtime->tm_mon + 1,
mtime->tm_mday,
mtime->tm_hour,
mtime->tm_min,
mtime->tm_sec,
dir_info->d_name);
}
return ;
}
int main(int argc, char **argv) {
if(argc != 2) {
printf("usage:cmd + pathname\n");
return 1;
}
ls_al(argv[1]);
return 0;
}
2021-08-25