用封装函数获取文件属性

stat.h文件

#ifndef __STAT_H__
#define __STAT_H__


//文件类型
char get_fileType(mode_t mode);
//文件权限
char* get_filePermission(mode_t mode, char* pstr);
//硬链接数
void get_filenlink(nlink_t nlink);
//文件所属用户
void get_filepasswd(uid_t uid);
//文件所属组用户
void get_filegroup(gid_t gid);
//文件大小
void get_filesize(off_t size);
//文件时间
void get_filetime(time_t time);

#endif

stat.c文件

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



//定义文件类型函数
char get_fileType(mode_t mode)
{
	if(S_ISREG(mode))
		return '-';
	else if(S_ISDIR(mode))
		return 'd';
	else if(S_ISCHR(mode))
		return 'c';
	else if(S_ISBLK(mode))
		return 'b';
	else if(S_ISFIFO(mode))
		return 'p';
	else if(S_ISLNK(mode))
		return 'l';
	else if(S_ISSOCK(mode))
		return 's';
}


//定义文件权限函数
char* get_filePermission(mode_t mode, char* pstr)
{
	char str[4] = {'r','w','x'};
	for(int i=0; i<9; i++)
	{
		if((mode & (0400>>i)) == 0)
		{
			pstr[i] = '-';
			continue;
		}
		//能运行到当前位置,则代表mode&(0400>>i)是不等于0;
		pstr[i] = str[i%3];
	}

	return pstr;
}

//文件硬链接数函数
void get_filenlink(nlink_t nlink)
{
	printf(" %ld", nlink);
}

//定义文件所属用户函数
void get_filepasswd(uid_t uid)
{
	struct passwd *pwd = getpwuid(uid);
	if(NULL == pwd)
	{
		perror("getpwuid");
		return;
	}
	printf(" %s", pwd->pw_name);
}


//文件所属组用户函数
void get_filegroup(gid_t gid)
{
	struct group* grp = getgrgid(gid);
	if(NULL == grp)
	{
		perror("getgrgid");
		return ;
	}
	printf(" %s", grp->gr_name);

}

//文件大小函数
void get_filesize(off_t size)
{
	printf(" %ld",size);
}
//文件的时间
void get_filetime(time_t time)
{
	char *mon[12] = {"一","二","三","四","五","六","七","八","九","十","十一","十二"};
	struct tm* info = localtime(&time);
	printf("%s %d %d:%d:%d",mon[info->tm_mon],info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
}

main.c头文件

#include <stdio.h> 
#include <sys/types.h>     
#include <sys/stat.h>
#include <unistd.h>
#include"stat.h"


int main(int argc, const char *argv[])
{
	struct stat buf;
	if(stat(argv[1],&buf) < 0)
	{
		perror("stat");
		return -1;
	}

	//调用文件类型函数
	char type = get_fileType(buf.st_mode);
	printf("%c",type);
	//调用文件权限函数
	char per[10] = "";
	get_filePermission(buf.st_mode,per);
	printf(" %s",per);
	//调用文件硬链接数函数
	get_filenlink(buf.st_nlink);
	//调用文件所属用户函数
	get_filepasswd(buf.st_uid);
	//调用文件所属组用户函数
	get_filegroup(buf.st_gid);
	//调用文件大小函数
	get_filesize(buf.st_size);
	//调用文件的时间函数
	get_filetime(buf.st_ctime);
	//文件名
	printf(" %s\n",argv[1]);
	return 0;
}

运行结果

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值