系统:任意的liunx系统
myls.c文件如下:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
char get_type(mode_t s)
{
/* switch(s & S_IFMT)
{
case S_IFSOCK: return 's';
case S_IFREG: return '-';
case S_IFDIR: return 'd';
case S_IFLNK: return 'l';
case S_IFIFO: return 'p';
case S_IFCHR: return 'c';
case S_IFBLK: return 'b';
}
*/
if(S_ISREG(s))return '-';
if(S_ISLNK(s))return 'l';
if(S_ISCHR(s))return 'c';
if(S_ISBLK(s))return 'b';
if(S_ISSOCK(s))return 's';
if(S_ISFIFO(s))return 'p';
if(S_ISDIR(s))return 'd';
}
char *get_per(mode_t s)
{
static char buf[10] = {0};
int i = 9;
while(i--)
{
buf[i] = '-';
if(s & 1<<(8-i) )
{
switch(i%3)
{
case 0: buf[i] = 'r';break;
case 1: buf[i] = 'w';break;
case 2: buf[i] = 'x';break;
}
}
}
return buf;
}
char *get_owner(uid_t uid)
{
return getpwuid(uid)->pw_name;
}
char *get_gro(gid_t gid)
{
return getgrgid(gid)->gr_name;
}
char *get_time(time_t t)
{
static char buf[100];
strncpy(buf, ctime(&t), 24);
return buf;
}
int main()
{
DIR *dp = opendir(".");
int sum = 0;
struct stat s;
struct dirent *p;
while( p = readdir(dp) )
{
stat(p->d_name, &s);
printf("%c%s %3d %s %s %8ld %s %s\n",
get_type(s.st_mode),
get_per(s.st_mode),
s.st_nlink,
get_owner(s.st_uid),
get_gro(s.st_gid),
s.st_size,
get_time(s.st_ctime),
p->d_name);
sum += s.st_size;
}
printf("total size(k): %d\n", sum/1024);
// printf( "\033[1;31;40m asdfasdfasdfasdf asdfa sdfa sda\033[0m" );
}