实现ls -l 操作,需要得到以下文件信息:文件类型,文件权限,链接数量,用户id,组id,最后修改时间,文件名
获取文件信息的原理,详见 文件 IO 笔记 获取文件属性方面
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <dirent.h>
int main(int argc, char const *argv[])
{
// 定义struct stat 类型的结构体变量
struct stat st;
struct dirent *p; // 定义结构体变量 接收 readir 返回值
DIR *dir = opendir("."); // 目录流
// 循环判断读取的文件
while ((p = readdir(dir)) != NULL)
{
stat(p->d_name, &st);
// 判断文件类型
// 通过位与运算得出文件类型
switch (st.st_mode & S_IFMT)
{
case S_IFREG:
printf("-");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
case S_IFIFO:
printf("f");
break;
case S_IFLNK:
printf("l");
break;
case S_IFBLK:
printf("b");
break;
case S_IFSOCK:
printf("s");
break;
default:
printf("mode err\n");
break;
}
// 用户权限
if (st.st_mode & S_IRUSR)
{
printf("r");
}
else
{
printf("-");
}
if (st.st_mode & S_IWUSR)
{
printf("w");
}
else
{
printf("-");
}
if (st.st_mode & S_IXUSR)
{
printf("x");
}
else
{
printf("-");
}
// 组员权限
if (st.st_mode & S_IRGRP)
{
printf("r");
}
else
{
printf("-");
}
if (st.st_mode & S_IWGRP)
{
printf("w");
}
else
{
printf("-");
}
if (st.st_mode & S_IXGRP)
{
printf("x");
}
else
{
printf("-");
}
// 其他人权限
if (st.st_mode & S_IROTH)
{
printf("r");
}
else
{
printf("-");
}
if (st.st_mode & S_IWOTH)
{
printf("w");
}
else
{
printf("-");
}
if (st.st_mode & S_IXOTH)
{
printf("x");
}
else
{
printf("-");
}
// 硬链接数
printf(" %d ", st.st_nlink);
// 用户名
printf(" %s", getpwuid(st.st_uid)->pw_name);
// 组名
printf(" %s", getgrgid(st.st_gid)->gr_name);
// 大小
printf(" %ld ", st.st_size);
// 修改时间
printf(" %.12s ", ctime(&st.st_mtime) + 4);
// 文件名
printf(" %s", p->d_name);
printf("\n");
}
return 0;
}