提取文件信息

头文件

#ifndef __STATFUNC_H__
#define __STATFUNC_H__
 
#include<fcntl.h> //只有调用fcntl.h才能用mode_t
 
//获取文件权限
void get_filePermission(mode_t mode);
 
//获取文件类型
char get_fileType(mode_t mode);
 
//获取文件所属用户
void get_filepasswd(mode_t uid);
 
//获取文件所属组用户
void get_filegroup(mode_t gid);
 
 
#endif

函数

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include"05_statfun.h"
#include <time.h>
#include<fcntl.h>
//获取文件权限
void get_filePermission(mode_t mode)
{
	int a=0400;
	char str[3]={'r','w','x'};
	for(int i=0;i<9;i++)
	{
		if(mode&a)
		{
			putchar(str[(i)%3]);
		}else
		{
			printf("-");
		}
		a=a>>1;
	}
}
//获取文件类型
char get_fileType(mode_t mode)
{
	char c = 0;
	switch(mode&S_IFMT)
	{
	case S_IFSOCK: 	c = 's'; break;
	case S_IFLNK: 	c = 'l'; break;
	case S_IFREG: 	c = '-'; break;
	case S_IFDIR: 	c = 'd'; break;
	case S_IFIFO: 	c = 'p'; break;
	case S_IFCHR: 	c = 'c'; break;
	case S_IFBLK: 	c = 'b'; break;
	}
 
 
	return c;
}
//获取文件所属用户
void get_filepasswd(mode_t uid)
{	
	struct passwd* pwd = getpwuid(uid);
	if(NULL == pwd)
	{
		perror("getpwuid");
		return ;
	}
	printf(" %s", pwd->pw_name);
}
 
//获取文件所属组用户
void get_filegroup(mode_t gid)
{
	struct group* grp = getgrgid(gid);
	if(NULL == grp)
	{
		perror("getgrgid");
		return ;
	}
	printf(" %s", grp->gr_name);
}

main

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include "05_statfun.h"
#include<time.h>
#include<fcntl.h>
int main(int argc, const char *argv[])
{
	struct stat buf;
	if(stat(argv[1],&buf)<0)
	{
		perror("stat");
		return -1;
	}
	char per[10]="";
	char type=0;
	//文件的类型以及权限
	type=get_fileType(buf.st_mode);
	printf("%c",type);
	get_filePermission(buf.st_mode);
 	//文件的硬链接数
	printf(" %ld",buf.st_nlink);
	//文件所属用户
	get_filepasswd(buf.st_uid);
	//文件所属组用户
	get_filegroup(buf.st_gid);
	//文件的大小
	printf(" %ld",buf.st_size);
	//文件的时间
	struct tm *t=NULL;
	t=localtime(&buf.st_ctime);
	printf(" %d %d %02d:%02d",t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min);
	
 
	//文件名
	printf(" %s\n",argv[1]);
	return 0;
}

结果 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值