linux 函数实现ls -l命令
2013-09-16 20:49
387 查看
linux 函数实现ls -l命令
#include <sys/types.h> #include <dirent.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <pwd.h> #include <grp.h> int mystat(char *str); DIR *dir; struct dirent *sd; struct stat stbuf; int main(int argc,char *argv[]) { int cdir; char *pwd=NULL; if (argc != 2){ fprintf(stderr, "Usage: %s <pathname>\n", argv[0]); } if(stat(argv[1],&stbuf)==-1){ fprintf(stderr,"stat error"); return; } if((stbuf.st_mode & S_IFMT)!=S_IFDIR){ mystat(argv[1]); printf("%s\n",argv[1]); } else{ cdir=chdir(argv[1]); if(cdir!=-1) pwd=getcwd(pwd,0); dir=opendir(pwd); if(dir==NULL){ fprintf(stderr,"can't open %s\n",argv[1]); return; } while((sd=readdir(dir))!=NULL){ mystat(sd->d_name); printf("%s\n",sd->d_name); } closedir(dir); } return 0; } int mystat(char *str) { struct stat sb; struct passwd *pas; struct group *gro; char *time; int n; char bit[9]; if(stat(str,&sb)==-1){ perror("stat"); exit(EXIT_FAILURE); } switch (sb.st_mode & S_IFMT) { case S_IFBLK: printf("b"); break; case S_IFCHR: printf("c"); break; case S_IFDIR: printf("d"); break; case S_IFIFO: printf("p"); break; case S_IFLNK: printf("l"); break; case S_IFREG: printf("-"); break; case S_IFSOCK: printf("s"); break; default: break; } pas=getpwuid(sb.st_uid); gro=getgrgid(sb.st_gid); time=ctime(&sb.st_atime); n=strlen(time); time[--n]='\0'; if(sb.st_mode & S_IRUSR) bit[0]='r'; else bit[0]='-'; if(sb.st_mode & S_IWUSR) bit[1]='w'; else bit[1]='-'; if(sb.st_mode & S_IXUSR) bit[2]='x'; else bit[2]='-'; if(sb.st_mode & S_IRGRP) bit[3]='r'; else bit[3]='-'; if(sb.st_mode & S_IWGRP) bit[4]='w'; else bit[4]='-'; if(sb.st_mode & S_IXGRP) bit[5]='x'; else bit[5]='-'; if(sb.st_mode & S_IROTH) bit[6]='r'; else bit[6]='-'; if(sb.st_mode & S_IWOTH) bit[7]='w'; else bit[7]='-'; if(sb.st_mode & S_IXOTH) bit[8]='x'; else bit[8]='-'; printf("%s ",bit); printf("%ld ", (long) sb.st_nlink); printf("%s %s ",pas->pw_name,gro->gr_name); printf("%lld ",(long long) sb.st_size); printf("%s ", time); return 0; }
相关文章推荐
- linux文件和目录操作(附ls命令实现)
- 在linux下代码实现ls -l 命令(利用移位 和 与 操作 对指定位的分离 )(指定位段的分离)
- Linux下ls命令的简单实现
- 实现Linux下的ls命令
- Linux下ls命令实现
- Linux下的 ls 命令的简单实现
- linux下实现ls()函数遍历目录
- 做linux第四次实验,看错实验要求,花了一个下午自己模拟着实现一个ls命令。。。。
- C语言拷贝文件函数实现(linux cp [source file] [target file] 命令的实现)
- Linux---Ls命令 初级实现
- Linux下用C++实现ls命令
- Linux中模拟shell实现ls命令(不加参数)
- Linux下ls命令的简单模拟实现
- Linux系统编程_1_目录读取(实现简单ls命令)
- linux编程实践4(实现ls -l命令)
- 在Linux下:用 C 语言实现 ls 命令
- Linux命令的实现 -- ls pwd cd
- C语言实现Linux系统下ls命令的过滤文件功能
- 使用linux-c编程实现简单的ls命令
- ls命令是怎样实现的,getdents64,linux-2.6.27.5