#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
int main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dp;
int n;
int i;
char s[30];
struct tm *ts;
struct stat p;
void ls(char *);
if(argc!=2)
{
printf("Put one filename!\n"); exit(1);
}
n=stat(argv[1],&p);
if(n<0)
{
printf("%s\n",strerror(errno)); exit(1);
}
n=p.st_mode&(017<<12);
switch (n)
{
case 0100000:ls(argv[1]);break;
case 0040000:{
if((dir=opendir(argv[1]))==NULL)
{
printf("%s\n",strerror(errno));exit(1);
}
while((dp=readdir(dir))!=NULL)
{
// strcpy(s,"../");
strcpy(s,argv[1]);
strcat(s,"/");
strcat(s,dp->d_name);
ls(s);
}
} break;
default:printf("Error:shoud input a file or a directory!\n"); break;
}
}
void ls(char *name)
{
int n,i;
struct tm *ts;
struct stat p;
n=stat(name,&p);
if(n<0)
{
printf("%s\n",strerror(errno)); exit(1);
}
/* file type*/
n=p.st_mode&(017<<12);
switch (n)
{
case 0140000:printf("s");break;
case 0120000:printf("l");break;
case 0100000:printf("-");break;
case 0060000:printf("b");break;
case 0040000:printf("d");break;
case 0020000:printf("c");break;
case 0010000:printf("p");break;
}
for(i=0,n=8;i<3;i++)
{
if(p.st_mode&(01<<n--))
printf("r");
else
printf("-");
if(p.st_mode&(01<<n--))
printf("w");
else
printf("-");
if(p.st_mode&(01<<n--))
printf("x");
else
printf("-");
}
/*
n=p.st_mode&(01<<8);
if(n==0400)
printf("r");
else
printf("-");
n=p.st_mode&(01<<7);
if(n==0200)
printf("w");
else
printf("-");
n=p.st_mode&(01<<6);
if(n==0100)
printf("x");
else
printf("-");
*/
/*number of hard link*/
printf("%4d",p.st_nlink);
/*user ID of owner*/
printf("%9d",p.st_uid);
/*group ID of owner*/
printf("%9d",p.st_gid);
/*size of the file*/
printf(" %d",p.st_size);
/*time of last modification*/
ts=localtime(&p.st_mtime);
printf(" %4d-%2d-%2d %2d:%2d:%2d\n",ts->tm_year+1900,ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
}