UC头条:在Linux上实现自定义的 ls命令

//ctimevoiddo_ls(chardirname[]);voiddostat(char*filename);voidshow_file_info(char*fname,structstat*buf);//voidmode_to_letters(intmode,charstr[]);char*uid_to_name(uid_tuid);char*gid_to_name(gid_tgid);intmain(intargc,char*argv[]){if(argc==1){do_ls('.');}else{while(--argc){printf('%s:\n',*(++argv));do_ls(*argv);}}return0;}voiddo_ls(chardirname[]){DIR*dir_ptr;//记录opendir后的返回值structdirent*direntp;//记录readdir后的返回值if((dir_ptr=opendir(dirname))==NULL){fprintf(stderr,'ls1:cannotopen%s\n',dirname);}else{while((direntp=readdir(dir_ptr))!=NULL){//printf('%s\n',direntp->d_name);dostat(direntp->d_name);}closedir(dir_ptr);}}voiddostat(char*filename){structstatinfo;//存储filename的信息if(stat(filename,&info)==-1){perror(filename);}else{show_file_info(filename,&info);}}voidshow_file_info(char*filename,structstat*info_p){//char*uid_t_name,*ctime,*gid_to_name;voidmode_to_letters;charmodestr[11];mode_to_letters(info_p->st_mode,modestr);//将模式字段转换成字符printf('%s',modestr);printf('%4d',(int)info_p->st_nlink);printf('%-10s',uid_to_name(info_p->st_uid));//将用户ID转换成字符串printf('%-10s',gid_to_name(info_p->st_gid));//将组ID转换成字符串printf('%8ld',(long)info_p->st_size);printf('%.12s',4+ctime(&info_p->st_mtim.tv_sec));//通过ctime函数转换时间,之前的who命令有用到printf('%s\n',filename);}//将模式字段转换成字符voidmode_to_letters(intmode,charstr[]){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';}//将用户ID转换成字符串char*uid_to_name(uid_tuid){//structpasswd*getpwuid,*pw_ptr;structpasswd*pw_ptr;staticcharnumstr[10];if((pw_ptr=getpwuid(uid))==NULL){sprintf(numstr,'%d',uid);returnnumstr;}else{returnpw_ptr->pw_name;}}//将组ID转换成字符串char*gid_to_name(gid_tgid){//structgroup*getgrgid,*grp_str;structgroup*grp_str;staticcharnumstr[10];if((grp_str=getgrgid(gid))==NULL){sprintf(numstr,'%d',gid);returnnumstr;}else{returngrp_str->gr_name;}}

(0)

相关推荐