作业:
输出文件相关属性。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
char *mon[12]={"一月","二月","三月","四月","五月","六月","七月"\
,"八月","九月","十月","十一月","十二月"};
char *get_file_permission(mode_t mode){
char *str=malloc(10);
int rwx = 0400;
char per[]="rwx";
int i=0;
for(;i<9;i++){
if(mode & rwx>>(i)){
*(str+i) = per[i%3];
}else{
*(str+i) = '-';
}
}
*(str+i) = '\0';
return str;
}
int main(int argc, const char *argv[])
{
struct stat buf;
const char *file = argv[1];
if(stat(file,&buf) < 0){
perror("stat");
return -1;
}
//mode_t unsigned int
//printf("mode:0%o\n",buf.st_mode);
printf("-%s ",get_file_permission(buf.st_mode));
printf("%lu ",buf.st_nlink);
//printf("uid:%d\n",buf.st_uid);
struct passwd *_passwd=getpwuid(buf.st_uid);
if(_passwd != NULL)
printf("%s ",_passwd->pw_name);
//printf("gid:%d\n",buf.st_gid);
struct group *_group=getgrgid(buf.st_gid);
if(_group != NULL)
printf("%s ",_group->gr_name);
printf("%ld ",buf.st_size);
//printf("time:%ld\n",buf.st_ctime);
struct tm *info = localtime(&buf.st_ctime);
/*
printf("%4d-%02d-%02d %02d:%02d:%02d\n",\
info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
*/
printf("%s %02d %02d:%02d %s\n",mon[info->tm_mon],\
info->tm_mday,info->tm_hour,info->tm_min,\
file);
return 0;
}
执行结果:
ubuntu@ubuntu:20230223_fileio$ ./a.out 3.txt
-rwxrwxrwx 1 ubuntu ubuntu 31 二月 23 13:50 3.txt
ubuntu@ubuntu:20230223_fileio$ ls -lh 3.txt
-rwxrwxrwx 1 ubuntu ubuntu 31 二月 23 13:50 3.txt