使用stat函数提取文件属性并打印文件信息。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <grp.h>
#include <time.h>

void get_file_type(mode_t st_mode){
	switch(st_mode&S_IFMT){
	case S_IFBLK:
		putchar('b');
		break;
	case S_IFCHR:
		putchar('c');
		break;
	case S_IFDIR:
		putchar('d');
		break;
	case S_IFREG:
		putchar('-');
		break;
	case S_IFLNK:
		putchar('l');
		break;
	case S_IFSOCK:
		putchar('s');
		break;
	case S_IFIFO:
		putchar('p');
		break;
	}
}
void get_filePermission(mode_t m,char ptr[10]){
	char str[4]="rwx";
	for(int i=0;i<9;i++){
		if((m&(0400>>i))==0){
			ptr[i]='-';
			continue;
		}
		ptr[i]=str[i%3];
	}
}
void get_file_pwdname(uid_t st_uid){
	char str[10]={0};
	struct passwd *name=getpwuid(st_uid);
	strcpy(str,name->pw_name);
	printf("%s ",str);
}
void get_file_groupname(gid_t st_gid){
	char str[10]={0};
	struct group *name=getgrgid(st_gid);
	strcpy(str,name->gr_name);
	printf("%s ",str);
}
void get_file_time(struct timespec st_mtim){
	struct tm* info;
	info=localtime(&st_mtim.tv_sec);
	printf("%02d %02d %02d:%02d",info->tm_mon+1,\
			info->tm_mday,info->tm_hour,info->tm_min);
}
int main(int argc, const char *argv[])
{
	struct stat buf;
	stat(argv[1],&buf);
	get_file_type(buf.st_mode);
	char ptr[10]="";
	get_filePermission(buf.st_mode,ptr);
	printf("%s",ptr);
	printf(" %ld ",buf.st_nlink);
    get_file_pwdname(buf.st_uid);
    get_file_groupname(buf.st_gid);
	printf("%ld ",buf.st_size);
	get_file_time(buf.st_mtim);
	printf(" %s\n",argv[1]);


	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值