#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
void showMode(int mode,char *p)
{
int flag = 0,cache = 0400,i = 0;
p[0] = '-';
for(i = 1;i <= 9;i++)
{
switch(! (mode & cache))
{
case 1:p[i] = '-';break;
case 0:{
switch(flag)
{
case 0:p[i] = 'r';break;
case 1:p[i] = 'w';break;
case 2:p[i] = 'x';break;
}
}
}
switch(flag)
{
case 0: case 1:flag++;break;
case 2: flag = 0;break;
}
cache >>= 1;
}
p[i] = '\0';
}
void showID(int id,char*p)
{
char count = 0,get = 0,j=0;
int sum = 0;
long i=0;
FILE* fp = fopen("/etc/passwd","r");
if(NULL == fp)
{
printf("%d\n",__LINE__);
perror("open");
return;
}
if(!strcmp(p,"uid"))
{
while(EOF != get )
{
sum = 0;
count = 0;
while(count<2)//找到文件中uid的位置
{
if((get=fgetc(fp)) == ':')
count++;
}
while((get=fgetc(fp)) <= '9'&& get >= '0')//字符转整型
{
sum = sum * 10 + (get - '0');
}
if(sum == id)//判断uid是否一致
{
while((get = fgetc(fp)) != '\n')//移动光标至需要获取的用户名字符串前
{
fseek(fp,0-2,SEEK_CUR);
}
i = 0;
while((get=fgetc(fp)) != ':')//获取用户名字符串
{
p[i++] = get;
}
p[i] = '\0';
return;
}
while((get = fgetc(fp)) != '\n' && EOF != get);
}
}
else if(!strcmp(p,"gid"))
{
while(EOF != get)
{
sum = 0;
count = 0;
while(count<3)//找到文件中uid的位置
{
if((get=fgetc(fp)) == ':')
count++;
}
while((get=fgetc(fp)) <= '9'&& get >= '0')//字符转整型
{
sum = sum * 10 + (get - '0');
}
if(sum == id)//判断uid是否一致
{
while((get = fgetc(fp)) != '\n')//移动光标至需要获取的用户名字符串前
{
fseek(fp,0-2,SEEK_CUR);
}
i = 0;
while((get=fgetc(fp)) != ':')//获取用户名字符串
{
p[i++] = get;
}
p[i] = '\0';
return;
}
while((get = fgetc(fp)) != '\n' && EOF != get);
}
}
printf("no such user\n");
return;
}
void showMon(int mon)
{
switch(mon)
{
case 1 :printf("一月");break;
case 2 :printf("二月");break;
case 3 :printf("三月");break;
case 4 :printf("四月");break;
case 5 :printf("五月");break;
case 6 :printf("六月");break;
case 7 :printf("七月");break;
case 8 :printf("八月");break;
case 9 :printf("九月");break;
case 10 :printf("十月");break;
case 11:printf("十一月");break;
case 12 :printf("十二月");break;
default:printf("输入错误\n");exit(0);
}
}
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat(argv[1],&buf) < 0)
{
perror("stat");
return 0;
}
struct tm *ti=NULL ;
ti=localtime(&(buf.st_ctime));
char mod[11],uid[10] = "uid",gid[10] = "gid";
showMode(buf.st_mode,mod);
showID(buf.st_uid,uid);
showID(buf.st_gid,gid);
printf("%s %lu %s %s %ld ",mod,buf.st_nlink,uid,gid,buf.st_size);
showMon(ti->tm_mon+1);
printf(" %d %d:%d %s\n",ti->tm_mday,ti->tm_hour,ti->tm_min,argv[1]);
return 0;
}