完成如下目标:
实现“ls -l”的基本功能,至少能输出文件类型、9个权限位信息、文件大小、文件名称
代码:
#include <dirent.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iomanip>
using namespace std;
#define FILE_NAME ". /"
//获取根目录下文件内容
int main (){
struct stat buf;
DIR *dir;
struct dirent *dirp;
if (!(dir=opendir(FILE_NAME))){
exit (-1) ;
}
//读取文件夹内表项
cout <<setw (20) <<left<<"FILE_NAME"<<"\t";
cout <<setw (10) <<left<<"FILE_SIZE"<"\t";
cout <<"\t";
cout <<setw (20) <<left<<"TYPE"<<"\t";
cout <<"ROLE";
cout <<endl;
//格式输出统一
while((dirp = readdir (dir))!=NULL){
//遍历文件
if(dirp-> d_name [0] =='. '){
continue;
}
string strline = "";
//存放文件类型
stat (dirp-> d_name, &buf) ;
if (S_ISREG(buf.st_mode))
strline = "regular";
else if (S_ISDIR (buf.st_mode))
strline = "directory";
else if (S_ISCHR (buf.st_mode))
strline = "character special";
else if (S_ISBLK(buf.st_mode))
strline = "block special";
else if (S_ISFIFO (buf.st_mode))
strline = "fifo";
else
strline = "** unknown mode **";
//通过比较获取文件类型
string strrole = "";
//存放文件权限位
if (buf.st_mode& S_IRUSR)strrole += "R";
else strrole += "_";
if (buf.st_mode&S_IWUSR)strrole += "W";
else strrole += "_";
if (buf.st_mode & S_IXUSR)strrole += "X";
else strrole += "_";
if (buf.st_mode & S_IRGRP)strrole +="R";
else strrole += "_";
if (buf.st_mode & S_IWGRP)strrole += "W";
else strrole += "-";
if (buf.st_mode& S_IXGRP)strrole += "X";
else strrole += "-";
if (buf.st_mode & S_IROTH)strrole += "R";
else strrole +="-";
if (buf.st_mode & S_IWOTH)strrole +="W";
else strrole += "-";
if (buf.st_mode & S_IXOTH)strrole += "X";
else strrole += "-";
//获取文件权限位信息
cout <<setw (20) <<left<<dirp->d_name<<"\t";
cout <<setw(10)<<left<<buf.st_size<<"\t";
cout <<setw (20) <<left<<strline<<"\t";
cout <<strrole;
cout <<endl;
//输出并格式化
}
return 0;
}
想获得其他输出,自行添加即可
效果展示: