编程实现 ls -l 命令所实现的功能
2013-09-22 20:25
169 查看
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <dirent.h> #include <string.h> #include <time.h> #include <grp.h> #include <pwd.h> char mode[10];/*声明一个存储权限的字符数组*/ void mode_info_my(mode_t st_mode,char *mode);/*函数声明*/
/*函数功能:按linux系统中ls -l命令格式,输出文件或者目录的信息*/ void my_stat(char *p) { char *time; int t; struct stat st_p; if(stat(p,&st_p) == -1) printf("stat error\n"); mode_info_my(st_p.st_mode,mode); printf("%s",mode); printf(" %ld",(long)st_p.st_nlink); printf(" %s",getpwuid(st_p.st_uid)->pw_name); printf(" %s",getgrgid(st_p.st_gid)->gr_name); printf(" %ld",(long)st_p.st_size); time=ctime(&st_p.st_ctime); t=strlen(time); time[t-1]='\0'; printf(" %s",time); }
/*函数功能:获取文件或者目录的权限信息*/ void mode_info_my(mode_t st_mode,char *mode) { if(S_ISREG(st_mode)) mode[0]='-'; if(S_ISDIR(st_mode)) mode[0]='d'; if(S_ISCHR(st_mode)) mode[0]='c'; if(S_ISBLK(st_mode)) mode[0]='b'; if(st_mode & S_IRUSR) mode[1]='r'; else mode[1]='-'; if(st_mode & S_IWUSR) mode[2]='w'; else mode[2]='-'; if(st_mode & S_IXUSR) mode[3]='x'; else mode[3]='-'; if(st_mode & S_IRGRP) mode[4]='r'; else mode[4]='-'; if(st_mode & S_IWGRP) mode[5]='w'; else mode[5]='-'; if(st_mode & S_IXGRP) mode[6]='x'; else mode[6]='-'; if(st_mode & S_IROTH) mode[7]='r'; else mode[7]='-'; if(st_mode & S_IWOTH) mode[8]='w'; else mode[8]='-'; if(st_mode & S_IXOTH) mode[9]='x'; else mode[9]='-'; } /*主函数*/ int main(int argc,char *argv[]) { struct stat st; struct dirent *dp; DIR *c; char p[256]; char *dir=NULL; if(argc == 1){ /*命令行只有一个参数情况,默认显示当前路径信息*/ argv[1]="."; } if(argc>2){ printf("command error\n"); return 1; } if(stat(argv[1],&st) != 0){ printf("fail to get stat of file\n"); return -1; } mode_info_my(st.st_mode,mode); if(mode[0] == 'd'){ /*路径为目录的相应操作*/ if((c=opendir(argv[1]))==NULL){ /*判断路径是否存在*/ printf("path is empty\n"); return -1; } if(chdir(argv[1])!=-1){ /*切换到所给路径*/ dir=getcwd(dir,0); } my_stat(dir); /*输出目录信息*/ while((dp=readdir(c)) != NULL){ /*遍历目录下的文件和目录,并输出其信息*/ strcpy(p,argv[1]); strcat(p,"/"); strcat(p,dp->d_name); /*文件路径连接*/ my_stat(p); /*打印信息*/ printf(" %s\n",dp->d_name);/*输出文件名*/ } } else /*参数是文件,输出文件信息*/ my_stat(argv[1]); return 0; }
相关文章推荐
- linux下使用系统调用编程实现dir命令功能
- 使用linux-c编程实现简单的ls命令
- 文件目录操作编程 实现“ls -l“功能
- 编程实现UNIX下ls-a的功能
- 编程实现cp命令功能
- (八)linux下编程实现ls功能的打开、访问 、关闭目录以及提取属性。
- C语言实现Linux系统下ls命令的过滤文件功能
- UNIX环境高级编程学习之第四章文件和目录-用C实现Shell中的"ls -l"功能
- Linux系统编程_1_目录读取(实现简单ls命令)
- Linux&C编程之Linux系统命令“ls -l”的简单实现
- 使用linux-c编程实现简单的ls命令
- UNIX环境高级编程学习之第六章系统数据文件和信息-修改第四章实现的Shell的“ls -l”功能
- linux编程实践4(实现ls -l命令)
- 编程实践----实现自己的ls命令
- linux下使用系统调用编程实现copy命令功能
- #写一个脚本实现如下功能: 输入一个数字,然后运行对应的>一个命令。显示命令如下:*cmd meau** 1—date 2–ls 3–who 4–pwd #当输入1时,会运行date, 输入2
- shell编程笔记六:实现ll命令
- Android网络编程之一个Android下菜单系统模块的实现(服务器端—添单功能)
- 软件中常见基础编程功能实现(不断改进加载中…)收藏
- Yum中实现与apt-get install build-essential功能类似的命令