1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include<sys/stat.h> #include<sys/types.h> #include<unistd.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<fcntl.h> #include<time.h> #include<grp.h> #include<pwd.h>
void mode_to_letters(int mode, char str[]) { strcpy(str, "----------"); if (S_ISDIR(mode)) { str[0] = 'd'; } if (S_ISCHR(mode)) { str[0] = 'c'; } if (S_ISBLK(mode)) { str[0] = 'b'; } 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'; } } char * uid_to_name(uid_t uid) { struct passwd *pw_ptr; static char numstr[10]; if((pw_ptr=getpwuid(uid))==NULL) { sprintf(numstr,"%d",uid); return numstr; } else { return pw_ptr->pw_name; } } char* gid_to_name(gid_t gid) { struct group *str; static char name_gid[10]; if((str=getgrgid(gid))==NULL) { sprintf(name_gid,"%d",gid); return name_gid; } else { return str->gr_name; } } int main(int argc,char *argv[]) { if(2!=argc) { perror("error input"); } chdir(argv[1]); DIR *dp=opendir(argv[1]); char name[11]; if(NULL==dp) { perror("cannot open the dir\n"); } struct dirent *entry; struct stat statbuf; while((entry=readdir(dp))!=NULL) { if(strcmp(entry->d_name,".")==0||strcmp(entry->d_name,"..")==0) { continue; } stat(entry->d_name,&statbuf); mode_to_letters(statbuf.st_mode,name); printf("%s",name); printf("%4d ",(int) statbuf.st_nlink); printf("%-13s",uid_to_name(statbuf.st_uid)); printf("%-13s",gid_to_name(statbuf.st_gid)); printf("%8ld ",(long) statbuf.st_size); printf("%.12s ",4+ctime(&statbuf.st_mtime)); printf("%s\n",entry->d_name); } }
|