代码如下:
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