【二十六】 Linux网络编程——模仿linux的ls命令实现
/*my_ls.c*/ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <pwd.h> #include <grp.h> #include <dirent.h> int display_file(char *argv,char *fname) { struct stat buf; struct tm *tp; if (lstat(argv, &buf) < 0) { perror("fail to lstat"); return -1; } switch (buf.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; } int n; for (n=8; n>=0; n--) { if (buf.st_mode & (1 << n)) { switch (n % 3) { case 2 : printf("r"); break; case 1 : printf("w"); break; case 0 : printf("x"); } } else { printf("-"); } } printf("%2d", buf.st_nlink); printf(" %s", getpwuid(buf.st_uid)->pw_name); printf(" %s", getgrgid(buf.st_gid)->gr_name); printf(" %8ld", buf.st_size); tp = localtime(&buf.st_mtime); printf(" %4d-%d-%d %2d:%2d", tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday, tp->tm_hour, tp->tm_min); printf(" %s\n", fname); return 0; } int main(int argc,char *argv[]) { struct stat buf; DIR *mydir; struct dirent *dirp; char path[256]; if (argc < 2) { printf("Usage : %s <file>\n", argv[0]); return -1; } if(lstat(argv[1],&buf)<0) { perror("fail to lstat"); return -1; } if((buf.st_mode & S_IFMT)==S_IFDIR) { mydir=opendir(argv[1]); while((dirp=readdir(mydir))!=NULL) { if(dirp->d_name[0]=='.') continue; sprintf(path,"%s/%s",argv[1],dirp->d_name); display_file(path,dirp->d_name); } } else { display_file(argv[1],argv[1]); } return 0; }