linux下C语言实现ls -l的功能

首先上图:

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;
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值