作业:提取文件信息

11test.h

#ifndef __11TEST_H__
#define __11TEST_H__

void get_file(mode_t mode);

char get_filetype(mode_t mode);
	
#endif

11test.c

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

void get_file(mode_t mode)
{
	int a = 0400;
	char arr[4] = "rwx";
	for (int i=0; i<9; i++)
	{
		if ((mode & a) != 0)
		{
			putchar(arr[i%3]);
		}else
		{
			putchar('-');
		}
		a = a>>1;
	}
}

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 'd';
	else if(S_ISSOCK(mode))
		return 'd';
}

10test.c

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "11test.h"
#include <pwd.h>
#include <grp.h>
#include <time.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);
	//printf("mode: %o\n",buf.st_mode);
	get_file(buf.st_mode); 

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

	//文件所属用户
	//printf("uid: %d ",buf.st_uid);
	struct passwd *uid = getpwuid(buf.st_uid);
	printf("%s ",uid->pw_name);
 
	//文件所属组用户
	//printf("gid: %d ",buf.st_gid);
	struct group *gid = getgrgid(buf.st_gid);
	printf("%s ",gid->gr_name);

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

	//文件的时间
	//printf("time: %ld",buf.st_ctime);
	struct tm *info = NULL;
	info = localtime(&buf.st_ctime);
	printf("%d  %d %02d:%02d",info->tm_mon+1,\
			info->tm_mday,info->tm_hour,info->tm_min);

	//文件名
	printf(" %s\n",argv[1]);

	return 0;
} 

运行结果;

ubuntu@ubuntu:io$ ./a.out 10test.c 
-rw-rw-r-- 1 ubuntu ubuntu 1072 12  7 21:04 10test.c
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值