通过文件函数打印出指定文件的信息
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
char * Month(int mon)
{
switch(mon)
{
case 0:
return "一月";
break;
case 1:
return "二月";
break;
}
}
char *get_filePermission(mode_t mode, char buf[10])
{
int i;
int a = 0400;
char per[] = "rwx";
bzero(buf, 10);
for(i=0; i<9; i++)
{
if((mode & a) == 0)
// putchar('-');
buf[i] = '-';
else
// putchar(per[i%3]);
buf[i] = per[i%3];
a = a>>1;
}
return buf;
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("./01_fileno.c", &buf) < 0)
{
perror("stat");
return -1;
}
char per[10] = "";
//文件类型以及权限
// printf("mode:0%o\n", buf.st_mode);
get_filePermission(buf.st_mode, per);
// printf("buf=%s", per);
// putchar(10);
//硬链接数
// printf("nlink: %lu\n", buf.st_nlink);
//文件所属用户
// printf("uid: %d\n", buf.st_uid);
struct passwd *_passwd;
uid_t uid = buf.st_uid;
_passwd = getpwuid(uid);
//文件所属组用户
// printf("gid: %d\n", buf.st_gid);
struct group *_group;
gid_t gid = buf.st_gid;
_group = getgrgid(gid);
//文件大小
// printf("size: %ld\n", buf.st_size);
//日期
// printf("time: %ld\n", buf.st_ctime);
struct tm *t1 = localtime(&buf.st_ctime);
int mon = t1->tm_mon;
int hour = t1->tm_hour;
int min = t1->tm_min;
// printf("%d\n", mon);
printf("%s %lu %s %s %ld %s %0d:%0d \n", per, buf.st_nlink, _passwd->pw_name,\
_group->gr_name, buf.st_size, Month(mon), hour, min);
return 0;
}
输出结果:
ubuntu@ubuntu:Day3$ gcc 06_stat.c
ubuntu@ubuntu:Day3$ ./a.out
rw-rw-r-- 1 ubuntu ubuntu 468 二月 10:32