ubuntu下 ls -l 命令的结果:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
char gettype(mode_t st_mode)
{
switch(S_IFMT & st_mode)
{
case S_IFSOCK:return 's';
case S_IFLNK:return 'l';
case S_IFREG:return '-';
case S_IFBLK:return 'b';
case S_IFDIR:return 'd';
case S_IFCHR:return 'c';
case S_IFIFO:return 'p';
}
}
char* getmode(mode_t st_mode)
{
static char mode[10]={0};
int i=9;
while(i--)
{
if(st_mode & (1<<i))
{
//rwxr-xr-x
switch(i%3)
{
case 0:
mode[8-i]='x';break;
case 1:
mode[8-i]='w';break;
case 2:
mode[8-i]='r';break;
}
}
else {
mode[8-i]='-';
}
}
return mode;
}
int main(int argc, char const* argv[])
{
struct tm *times;
struct stat sb;
struct dirent *pdir;
DIR *dirp=opendir(argv[1]);
if(dirp==NULL)
{
perror("opendir");
exit(1);
}
while(pdir=readdir(dirp))
{
if((strncmp(pdir->d_name,".",1)==0) || (strcmp(pdir->d_name,"..")==0))
continue;
stat(pdir->d_name,&sb);
times=localtime(&sb.st_mtime);
printf("%c%s %lu %s %s %lu %d月 %d %d:%d %s\n",gettype(sb.st_mode),getmode(sb.st_mode),sb.st_nlink,getpwuid(sb.st_uid)->pw_name,getgrgid(sb.st_gid)->gr_name,sb.st_size,times->tm_mon+1,times->tm_mday,times->tm_hour,times->tm_min,pdir->d_name);
}
return 0;
}