使用指令ls -l
编译ll.c 并运行
需要的头文件,通过man命令查阅即可
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <time.h>
#include <dirent.h>
#include <grp.h>
void month(int month)
{
if(month < 0 || month > 11)
{
printf("error");
return ;
}
switch(month)
{
case 0:
printf("jan");
break;
case 1:
printf("feb");
break;
case 2:
printf("mar");
break;
case 3:
printf("apr");
break;
case 4:
printf("may");
break;
case 5:
printf("jun");
break;
case 6:
printf("jul");
break;
case 7:
printf("aug");
break;
case 8:
printf("sep");
break;
case 9:
printf("oct");
break;
case 10:
printf("nov");
break;
case 11:
printf("dec");
break;
}
}
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("input error");
return -1;
}
DIR *dir = opendir(argv[1]);
if(dir == NULL)
{
printf("open error");
return -1;
}
struct dirent *dt;
while(dt = readdir(dir))
{
if(dt->d_name[0] == '.')
continue;
struct stat statbuf;
if(-1 == lstat(dt->d_name, &statbuf)){
perror("stat");
return -1;
}
switch(statbuf.st_mode&S_IFMT)
{
case S_IFSOCK:
printf("s");
break;
case S_IFLNK:
printf("l");
break;
case S_IFREG:
printf("-");
break;
case S_IFBLK:
printf("b");
break;
case S_IFDIR:
printf("d");
break;
case S_IFCHR:
printf("c");
break;
case S_IFIFO:
printf("p");
break;
}
int n = 8;
while(n-->=0)
{
if(statbuf.st_mode & 1 << n)
{
switch(n%3)
{
case 2:
printf("r");
break;
case 1:
printf("r");
break;
case 0:
printf("x");
break;
}
}else
{
printf("-");
}
}
printf(" %ld",statbuf.st_nlink);
printf(" %s ",getpwuid(statbuf.st_uid)->pw_name);
printf(" %s ",getgrgid(statbuf.st_gid)->gr_name);
printf(" %5ld ",statbuf.st_size);
struct tm *tp = localtime(&statbuf.st_mtime);
month(tp->tm_mon);
printf(" %2d %2d:%2d",tp->tm_mday,tp->tm_hour,tp->tm_min);
printf(" %s\n",dt->d_name);
}
closedir(dir);
return 0;