编程实现 ls -l 命令所实现的功能

来源:互联网 发布:linux ll命令结果显示 编辑:程序博客网 时间:2024/04/29 09:11
#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';elsemode[1]='-';if(st_mode & S_IWUSR)mode[2]='w';elsemode[2]='-';if(st_mode & S_IXUSR)mode[3]='x';elsemode[3]='-';if(st_mode & S_IRGRP)mode[4]='r';elsemode[4]='-';if(st_mode & S_IWGRP)mode[5]='w';elsemode[5]='-';if(st_mode & S_IXGRP)mode[6]='x';elsemode[6]='-';if(st_mode & S_IROTH)mode[7]='r';elsemode[7]='-';if(st_mode & S_IWOTH)mode[8]='w';elsemode[8]='-';if(st_mode & S_IXOTH)mode[9]='x';elsemode[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;}