C语言实现Linux中的ls -l命令源码
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <time.h> #include <pwd.h> void function(struct stat*statbuf) { int n = 8; 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; } while(n >= 0) { if(statbuf->st_mode & 1 << n){ //1 0000 0000 switch(n % 3){ case 2: printf("r"); break; case 1: printf("w"); break; case 0: printf("x"); break; } }else{ printf("-"); } n--; } printf(" "); } int main(int argc, char *argv[]) { struct stat* buff=(struct stat*)malloc(sizeof(struct stat)); struct tm* t; struct passwd* ursname,*groupname; ursname=(struct passwd*)malloc(sizeof(struct passwd)); size_t t0; DIR* d1=opendir("./"); if(d1==NULL) perror("open"); struct dirent*dir=readdir(d1); while(dir!=NULL) { if(dir->d_name[0]!=.) { stat(dir->d_name,buff); t0=buff->st_mtime; function(buff); t=localtime(&t0); ursname=getpwuid(buff->st_uid); groupname=getpwuid(buff->st_gid); if(t->tm_hour/10==0&&t->tm_min/10!=0) { fprintf(stdout,"%ld %s %s %ld %d %d 0%d:%d %-s ", buff->st_nlink, ursname->pw_name, groupname->pw_name, buff->st_size, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, dir->d_name); } else if(t->tm_min/10==0&&t->tm_hour/10!=0) { fprintf(stdout,"%ld %s %s %ld %d %d %d:0%d %-s ", buff->st_nlink, ursname->pw_name, groupname->pw_name, buff->st_size, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, dir->d_name); } else if(t->tm_hour/10==0&&t->tm_min/10==0) { fprintf(stdout,"%ld %s %s %ld %d %d 0%d:0%d %-s ", buff->st_nlink, ursname->pw_name, groupname->pw_name, buff->st_size, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, dir->d_name); } else { fprintf(stdout,"%ld %s %s %ld %d %d %d:%d %-s ", buff->st_nlink, ursname->pw_name, groupname->pw_name, buff->st_size, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, dir->d_name); } dir=readdir(d1); }else { dir=readdir(d1); } } closedir(d1); return 0; }
运行结果:
ls -l结果: