作业:获取文件属性

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

//提取文件权限
void get_mode(mode_t m)
{
	for (int i=0; i<9; i++)
	{
		char arr[] = "rwx";
		if((m & (0400>>i)) == 0)
		{
			putchar('-');	
			continue;
		}
		/*
		   switch(i%3)                                                                            
		   {                                                                                      
		   case 0:                                                                                
		   putchar('r');                                                                      
		   break;                                                                             
		   case 1:                                                                                
		   putchar('w');                                                                      
		   break;                                                                             
		   case 2:                                                                                
		   putchar('x');                                                                      
		   break;                
		   }
		   */

		putchar(arr[i%3]);
	}
}

//提取文件类型
void get_type(mode_t m)
{
	if(S_ISREG(m))
		putchar('-');
	else if(S_ISDIR(m))
		putchar('d');
	else if(S_ISCHR(m))
		putchar('c');
	else if(S_ISBLK(m))
		putchar('b');
	else if(S_ISFIFO(m))
		putchar('p');
	else if(S_ISLNK(m))
		putchar('l');
	else if(S_ISSOCK(m))
		putchar('s');
}


int main(int argc, const char *argv[])
{
	//获取文件属性
	struct stat buf;
	if(stat("./01test.c", &buf) < 0)
	{	
		perror("stat");
		return -1;
	}

	//文件类型及权限
	//printf("mode:%d : 八进制%o\n", buf.st_mode, buf.st_mode);
	get_type(buf.st_mode);
	get_mode(buf.st_mode);

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

	//文件所属用户名
	//printf("uid:%d\n", buf.st_uid);
	//get_uid(buf.st_uid);
	struct passwd* usr = getpwuid(buf.st_uid);
	if (NULL == usr)
	{
		perror("getpwuid");              
		return -1;
	}
	printf("%s ", usr->pw_name);

	//文件所属组用户名
	//printf("gid:%d\n", buf.st_gid);
	struct group* grp = getgrgid(buf.st_gid);    
	if (NULL == grp)
	{
		perror("getgrgid");              
		return -1;
	}
	printf("%s ", grp->gr_name);


	//文件大小
	printf("%ld ", buf.st_size);

	//文件时间
	//printf("time:%ld\n", buf.st_ctime);
	struct tm* info = NULL;                                          
	info = localtime(&buf.st_ctime);

	printf("%02d-%02d %02d:%02d",
			info->tm_mon+1, info->tm_mday,info->tm_hour,\
			info->tm_min);


	//文件名字
	printf(" 01test.c\n");

	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值