#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
char *get_filePermission(mode_t m,char ptr[10],int size)
{
char per[]="rwx";
for(int i=0;i<9;i++)
{
if((m&(0400>>i))==0)
{
// putchar('-');
ptr[i]='-';
}else
{
// printf("%c",per[i%3]);
ptr[i]=per[i%3];
}
}
return ptr;
}
void get_fileType(mode_t m)
{
switch(m & S_IFMT)
{
case S_IFSOCK: putchar('s'); break;
case S_IFLNK: putchar('l'); break;
case S_IFREG: putchar('-'); break;
case S_IFBLK: putchar('b'); break;
case S_IFDIR: putchar('d'); break;
case S_IFCHR: putchar('c'); break;
case S_IFIFO: putchar('p'); break;
default: printf("mode错误\n");
}
}
char *get_month(int mon)
{
switch(mon)
{
case 0:
return "Jan";
break;
case 1:
return "Feb";
break;
case 2:
return "Mar";
break;
case 3:
return "Apr";
break;
case 4:
return "May";
break;
case 5:
return "Jun";
break;
case 6:
return "Jul";
break;
case 7:
return "Aug";
break;
case 8:
return "Sep";
break;
case 9:
return "Oct";
break;
case 10:
return "Nov";
break;
case 11:
return "Dec";
break;
default:
break;
}
}
void print_time(time_t t)
{
struct tm *info = localtime(&t);
if (NULL == info)
{
perror("localtime");
return;
}
printf(" %s %02d %02d:%02d",\
get_month(info->tm_mon),info->tm_mday,\
info->tm_hour,info->tm_min);
fflush(stdout);
}
int main(int argc, const char *argv[])
{
if(argc<2)
{
fprintf(stderr,"输入文件名\n");
return -1;
}
//获取文件属性
struct stat buf;
if(stat(argv[1],&buf)<0)
{
perror("stat");
return -1;
}
//文件的类型以及权限
//printf("mode:%d 八进制:%o\n",buf.st_mode,buf.st_mode);
get_fileType(buf.st_mode);//调用
char str[10]="";
if( get_filePermission(buf.st_mode,str,sizeof(str))==NULL)
{
printf("文件权限获取失败\n");
return -1;
}
printf("%s",str);
//文件的硬链接数
printf(" %ld",buf.st_nlink);
//文件的所属用户名
// printf(" %d",buf.st_uid);
struct passwd* usr=getpwuid(buf.st_uid);//调用
if(NULL==usr)
{
perror("getpwuid");
return -1;
}
printf(" %s",usr->pw_name);
//文件所属组用户名
// printf(" %d ",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);
//文件的时间
print_time(buf.st_ctime);
fprintf(stdout," %s\n",argv[1]);
return 0;
}
结果为