Linux命令简单实现 -- ls

/* * ls.c * * Created on: May 6, 2011 * Author: bertrand */ #include <stdio.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> #include <pwd.h> #include <grp.h> #include <time.h> void file_mode(int mode) { char str[] = "----------"; if(S_ISDIR(mode)) str[0] = 'd'; else if(S_ISCHR(mode)) str[0] = 'c'; else if(S_ISBLK(mode)) str[0] = 'b'; else if(S_ISLNK(mode)) str[0] = 'l'; if(mode & S_IRUSR) str[1] = 'r'; if(mode & S_IWUSR) str[2] = 'w'; if(mode & S_IXUSR) str[3] = 'x'; if(mode & S_IRGRP) str[4] = 'r'; if(mode & S_IWGRP) str[5] = 'w'; if(mode & S_IXGRP) str[6] = 'x'; if(mode & S_IROTH) str[7] = 'r'; if(mode & S_IWOTH) str[8] = 'w'; if(mode & S_IXOTH) str[9] = 'x'; printf("%s ", str); } void file_nlink(int nlink) { printf("%4d ", nlink); } void file_user(uid_t uid) { struct passwd *pwd; if((pwd = getpwuid(uid)) == NULL) printf("%-8d", uid); else printf("%-8s", pwd->pw_name); } void file_grp(gid_t gid) { struct group *grp; if((grp = getgrgid(gid)) == NULL) printf("%-8d", gid); else printf("%-8s", grp->gr_name); } void file_size(long size) { printf("%8ld ",size); } void file_time(struct timespec mtim) { printf("%.12s ", 4 + ctime(&mtim)); } void file_name(char *name) { printf("%s/n",name); } void display_file(char *filename) { struct stat info; if(stat(filename, &info) == -1) { printf("%s: Can't get information/n",filename); return; } file_mode(info.st_mode); file_nlink(info.st_nlink); file_user(info.st_uid); file_grp(info.st_gid); file_size(info.st_size); file_time(info.st_mtim); file_name(filename); } void search_dir(char *path) { DIR *dp; struct dirent *dirp; if((dp = opendir(path)) == NULL) { printf("Can't open %s!/n", path); return; } while((dirp = readdir(dp)) != NULL) { display_file(dirp->d_name); } closedir(dp); } int main(int argc, char **argv) { int i; if(argc == 1) { search_dir("."); } else { for(i = 1; i < argc; i++) { printf("Display %s:/n", argv[i]); search_dir(argv[i]); } } return 0; }  

你可能感兴趣的:(Linux命令简单实现 -- ls)