获取文件属性

代码如下:

test.h函数声明文件:

#ifndef __TEST_H
#define __TEST_H

//获取文件类型函数
char get_fileType(mode_t mode);

//获取文件权限函数
void get_filePermission(mode_t mode);

//获取文件所属用户函数

//获取文件所属组用户函数
//获取文件大小函数
//获取文件时间函数
void time_fun();



#endif

13test.c定义函数文件:

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


//获取文件类型函数
char get_fileType()
{
	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';
}

//获取文件权限函数
void get_filePermission(mode_t mode)
{
	unsigned int a = 0400;
	for(int i=0;i<9;i++)
	{
		if((mode & 0400>>i) == 0)
		{
			putchar('-');
			continue;
		}
		switch(i%3)
		{
		case 0:
			putchar('r');
			break;
		case 1:
			putchar('w');
			break;
		case 2:
			putchar('x');		
		}
	}
	putchar(' ');
}

//获取文件时间函数
void time_fun(mode_t mode)
{
	time_t t1,t2;
	struct tm* info = NULL;
		t2 = time(&t1);
		info = localtime(&t1);
		char * str[] = {"一","二","三","四","五","六","七","八","九","十","十一","十二"};
		printf("%s\t",str[info->tm_mon]);
		printf("%d %d:%d ",info->tm_mday,\
				info->tm_hour,info->tm_min);
}

主函数文件:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "test.h"
#include <pwd.h>
#include <grp.h>
int main(int argc, const char *argv[])
{
	struct stat buf;
	if(stat(argv[1],&buf)<0)
	{
		perror("stat");
		return -1;
	}
	char type = 0;
	//文件的类型以及权限
	type = get_fileType(buf.st_mode);
	printf("%c",type);
	get_filePermission(buf.st_mode);

	//文件的硬链接数
	printf("%ld ",buf.st_nlink);

	//文件的所属用户
	struct passwd *pwd = getpwuid(buf.st_uid);
	if(NULL == pwd)
	{
		perror("getpwuid");
		return -1;
	}
	printf("%s ",pwd->pw_name);

	//文件的所属组用户
	struct group *grp = getgrgid(buf.st_gid);
	if(NULL == grp)
	{
		perror("getgrgid");
		return -1;
	}
	printf("%s ",grp->gr_name);
	//文件的大小
	printf("%6ld ",buf.st_size);

	//文件的时间
	//printf("%ld ",buf.st_ctime);
	time_fun();

	//文件的名称
	printf("%s\n",argv[1]);
	return 0;
}

终端执行结果:

ubuntu@ubuntu:IO$ gcc 12test.c 13test.c 
ubuntu@ubuntu:IO$ ./a.out 1.txt 
-rw-rw-r-- 1 ubuntu ubuntu     27 十二	7 20:6 1.txt
ubuntu@ubuntu:IO$ ./a.out 12test.c 
-rw-rw-r-- 1 ubuntu ubuntu    950 十二	7 20:6 12test.c

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鱼YY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值