#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
char *get_file(mode_t m,char pt[10])
{
char c[4]="rwx";
int i=0;
//int t=0400;
while(i<9)
{
if((m & (0400>>i))==0)
{
pt[i]='-';
i++;
continue;
}
pt[i]=c[i%3];
i++;
}
return pt;
}
//提取文件类型
char get_wjm(mode_t m)
{
switch(m&S_IFMT)
{
case S_IFSOCK: return('s'); break;
case S_IFLNK: return('l'); break;
case S_IFREG: return('-'); break;
case S_IFDIR: return('d'); break;
case S_IFBLK: return('b'); break;
case S_IFCHR: return('c'); break;
case S_IFIFO: return('p'); break;
default:return 0;
}
}
char *get_ssyhm(uid_t uid,char *pt)
{
struct passwd *pwd =getpwuid(uid);
if(pwd == NULL)
{
return NULL;
}
strcpy(pt,pwd->pw_name);
return pwd->pw_name;
}
char *get_sszyh(uid_t gid,char *pt)
{
struct group *grp=getgrgid(gid);
if(grp == NULL)
{
return NULL;
}
strcpy(pt,grp->gr_name);
return pt;
}
void get_time(long int a)
{
struct tm *info=NULL;
info= localtime(&a);
printf("%02d %02d %02d %02d:%02d",\
info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
}
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;
}
char b;
char c[10];
char name1[20];
char name2[20];
//printf("st_mode :%o\n",buf.st_mode);
b=get_wjm(buf.st_mode);
printf(" %c ",b);
get_file(buf.st_mode,c);
printf(" %s ",c);
get_ssyhm(buf.st_uid,name1);
printf(" %s ",name1);
get_sszyh(buf.st_gid,name2);
printf(" %s ",name2);
//printf("st_nlink :%ld\n",buf.st_nlink);
//printf("st_mode :%d\n",buf.st_uid);
//printf("st_mode :%d\n",buf.st_gid);
printf(" %ld ",buf.st_size);
// printf("st_mode :%ld\n",buf.st_ctime);
get_time(buf.st_ctime);
printf(" %s ",argv[1]);
return 0;
}
运行结果是这样的