首先上图:
ls- l效果图
ls -l 是查看文件的详细信息:
主要包括:文件类型,权限信息,所有者信息,所有组信息,文件大小,时间,文件名。
补充:
(1)判断文件类型的方法
buf.st_mode & S_IFMT 的值等于哪一个文件类型的宏,那么这个文件就是该类型
S_IFMT 0170000 bit mask for the file type bit fields
S_IFSOCK 0140000 socket//套接字文件
S_IFLNK 0120000 symbolic link//符号链接
S_IFREG 0100000 regular file//普通文件
S_IFBLK 0060000 block device//块设备文件
S_IFDIR 0040000 directory//目录文件
S_IFCHR 0020000 character device//字符设备文件
S_IFIFO 0010000 FIFO
(2)判断权限(权限按8字节存储)
buf.st_mode & 权限对应宏 == 权限本身 则拥有该权限
所属者权限
{
S_IRUSR 00400 owner has read permission
S_IWUSR 00200 owner has write permission
S_IXUSR 00100 owner has execute permission
}
所属组权限
{
S_IRGRP 00040 group has read permission
S_IWGRP 00020 group has write permission
S_IXGRP 00010 group has execute permission
}
其他人权限
{
S_IROTH 00004 others have read permission
S_IWOTH 00002 others have write permission
S_IXOTH 00001 others have execute permission
}
上代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
int main(int argc, char *argv[])
{
struct dirent *file = NULL;
struct stat buf;
struct tm *myt = NULL;
int ret = 0;
int i = 0;
DIR *dir = opendir(".");
if(dir == NULL)
{
perror("opendir");
return -1;
}
while((file = readdir(dir)) != NULL)
{
if(file->d_name[0] != '.')//除去隐藏文件
{
ret = lstat(file->d_name, &buf);//获取文件属性
if(ret < 0)
{
perror("latat");
return -1;
}
myt = localtime(&buf.st_mtime);//获取时间
switch(buf.st_mode & S_IFMT)
{
case S_IFSOCK:printf("s");break;//套接字
case S_IFLNK: printf("l");break;//链接
case S_IFREG: printf("-");break;//普通文件
case S_IFBLK: printf("b");break;//块设备文件
case S_IFDIR: printf("d");break;//目录文件
case S_IFCHR: printf("c");break;//字符设备文件
case S_IFIFO: printf("p");break;//管道文件
}
char arr[3] = {'r', 'w', 'x'};//利用循环得到对应的权限值
for(i=0;i<9;i++)
{
printf("%c",buf.st_mode & (0400>>i) ? arr[i%3] : '-');
}
printf(" %ld ",buf.st_nlink);//硬链接数
printf(" %s ",getpwuid(buf.st_uid)->pw_name);//所有者名字
printf("%s ",getgrgid(buf.st_gid)->gr_name);//所属组名字
printf("%-8ld ",buf.st_size);//内存大小
printf("%d月 %d %02d:%02d ", myt->tm_mon+1, myt->tm_mday, myt->tm_hour, myt->tm_min);//时间
printf("%s\n",file->d_name);//文件名
}
}
return 0;
}