【操作系统】实验6-仿写Linux下的ls-s命令(转载)
#include<iostream>
#include<dirent.h>
#include<sys/stat.h>
#include<string.h>//memcmp()
#include<grp.h>//getgrgid
#include<unistd.h>//getcwd
#include<pwd.h>//getpwuid
#include<cstdio>
using namespace std;
int ls(char *dirpath);
int ls_l(char *dirpath);
char filename[100][255];
int filenum = 0;
int main(int args,char* argv[]) {
cout<<"180511315刘东旭"<<endl;
char dir[255];
getcwd(dir,255);
if( args > 1){
ls_l(dir);
}else{
ls(dir);
}
return 0;
}
int ls(char *dirpath){
DIR *dir;
struct dirent *file;
struct stat info;
if(!(dir = opendir(dirpath))){
cout<<"fail to read"<<dirpath;
return -1;
}
while((file = readdir(dir))!= NULL){
if(strncmp(file->d_name, ".", 1) == 0)
continue;
stat(file->d_name,&info);
cout<<file->d_name<<endl;
}
cout<<endl;
closedir(dir);
return 1;
}
void power(int mode, char str[]){
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';
}
int ls_l(char *dirpath){
DIR *dir;
struct dirent *file;
struct stat info;
if(!(dir = opendir(dirpath))){
cout<<"fail to read"<<dirpath;
return -1;
}
struct passwd *userinfo;
struct group *groupinfo;
while((file = readdir(dir))!= NULL){
if(strncmp(file->d_name, ".", 1) == 0)
continue;
strcpy(filename[filenum++],file->d_name);
stat(file->d_name,&info);
userinfo = getpwuid(info.st_uid);
groupinfo = getgrgid(info.st_gid);
char pw[11];
power(info.st_mode,pw);
cout<<pw<<" " <<info.st_nlink<<" "<< userinfo->pw_name<<" "<<groupinfo->gr_name<<" "<<info.st_size<<" ";
printf(" %.12s", 4 + ctime(&info.st_mtime));
cout<<" "<<file->d_name;
cout<<endl;
}
closedir(dir);
return 1;
}
转载自:https://blog.csdn.net/qq_43650979/article/details/104751067
(如有侵权,请联系我删除)