目的:练习文件IO的使用
具体代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
int main(int argc, const char *argv[])
{
// 打开当前目录
DIR *dirp = opendir("./");
if (dirp == NULL) // 容错判断
{
perror("opendir err");
return -1;
}
// 遍历目录中的文件,并输出相关属性
struct dirent *dir; // 定义一个目录类型结构体
struct stat st; // 定义一个属性类型结构体
int st_ct;
while ((dir = readdir(dirp)) != NULL) // 遍历获取文件赋给dir
{
st_ct = stat(dir->d_name, &st); // 将文件属性赋给结构体st
if (st_ct == -1) // 容错判断
{
perror("stat err");
return -1;
}
// 文件类型(目录/普通文件)
if (S_ISREG(st.st_mode))
putchar('d');
else if (S_ISDIR(st.st_mode))
putchar('-');
// 用户权限
if (st.st_mode & S_IRUSR)
putchar('r');
else
putchar('-');
if (st.st_mode & S_IWUSR)
putchar('w');
else
putchar('-');
if (st.st_mode & S_IXUSR)
putchar('x');
else
putchar('-');
// 同组权限
if (st.st_mode & S_IRGRP)
putchar('r');
else
putchar('-');
if (st.st_mode & S_IWGRP)
putchar('w');
else
putchar('-');
if (st.st_mode & S_IXGRP)
putchar('x');
else
putchar('-');
// 其他权限
if (st.st_mode & S_IROTH)
putchar('r');
else
putchar('-');
if (st.st_mode & S_IWOTH)
putchar('w');
else
putchar('-');
if (st.st_mode & S_IXOTH)
putchar('x');
else
putchar('-');
printf(" ");
// 链接数
printf("%4ld ", st.st_nlink);
// 用户名
printf("%4s ", getpwuid(st.st_uid)->pw_name);
// 组名
printf("%4s ", getgrgid(st.st_gid)->gr_name);
// 大小
printf("%8ld ", st.st_size);
//访问日期
printf("%.12s ", ctime(&st.st_mtime)+4);
// 文件名
printf("%s", dir->d_name);
printf("\n");
}
return 0;
}
效果展示(与终端对比)
通过对比发现,基本的功能已经实现。但与正版的还是有所不同(山寨的就是逊啦~):
1.没有按照文件名长短进行排序输出,其次在各项文件属性输出时。
2.实现根据单项数据的最大位数动态控制输出格式。
这两个问题由于我所学知识有限,暂时没有什么简单的办法实现,如果各位前辈有好的思路还请指点一下,感谢!!!