欢迎关注大数据技术架构与案例微信公众号:过往记忆大数据
过往记忆博客公众号iteblog_hadoop
欢迎关注微信公众号:
过往记忆大数据

编写自己的ls程序

本程序用来仿照linux中的ls -l命令来实现的,主要运用的函数有opendir,readdir, lstat等。代码如下:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <algorithm>
using namespace std;

void getFileAndDir(vector<string> &, char *);
void displayFileDistribute(vector<string> &);

int main(int argc ,char *argv[]){
	vector<string> file;

	if(argc != 2){
		cerr << "usage: ls /XXX" << endl;
		exit(1);
	}

	getFileAndDir(file, argv[1]);
	displayFileDistribute(file);

	/*vector<string>::iterator it = file.begin();
	for(; it != file.end(); ++it){
		//cout << *it << endl;
	}*/

	exit(0);	
}

void getFileAndDir(vector<string> &file, char *dirName){
	DIR *dir;
	struct dirent *drt;

	dir = opendir(dirName);
	if(dir == NULL){
		cerr << "Cann't opendir " << dirName << endl;
		exit(1);
	}

	while((drt = readdir(dir)) != NULL){
		//cout << drt->d_name << endl;
		if(!strcmp(drt->d_name, ".") || !strcmp(drt->d_name, "..")){
			continue;
		}
		file.push_back(drt->d_name);
	}

	closedir(dir);
}

void displayFileDistribute(vector<string> &file){
	vector<string>::iterator it = file.begin();
	struct stat filestat;
	string perm[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
	cout << "总计 " << file.size() << endl;
	sort(file.begin(), file.end());
	for(; it != file.end(); ++it){
		if(lstat((*it).c_str(), &filestat) == -1){
			cerr << "stat filed!" << endl;
			continue;
		}
		cout << filestat.st_ino << " "; //inode
		
		if(S_ISREG(filestat.st_mode))
			cout << "-";
		else if(S_ISDIR(filestat.st_mode))
			cout << "d";
		else if(S_ISCHR(filestat.st_mode))
			cout << "c";
		else if(S_ISBLK(filestat.st_mode))
			cout << "b";
		else if(S_ISFIFO(filestat.st_mode))
			cout << "p";
		else if(S_ISLNK(filestat.st_mode))
			cout << "l";
		else if(S_ISSOCK(filestat.st_mode))
			cout << "s";
		else
			cout << "X";
		
		//get perm
		int i = 3;
		unsigned int mask = 0700;
		while(i > 0){
			cout << perm[(filestat.st_mode & mask) >> (i - 1) * 3];
			--i;
			mask >>= 3;
		}
		
		cout << " " << filestat.st_uid << " ";
		cout << filestat.st_gid << " ";
		string str = ctime(&filestat.st_atime); 
		cout << str.substr(0, str.length() - 9) << " ";
		cout << *it << endl;
	}


}

编译运行代码:程序需要接收一个目录参数比如 ./ls /home/wyp

本博客文章除特别声明,全部都是原创!
原创文章版权归过往记忆大数据(过往记忆)所有,未经许可不得转载。
本文链接: 【编写自己的ls程序】(https://www.iteblog.com/archives/186.html)
喜欢 (0)
分享 (0)
发表我的评论
取消评论

表情
本博客评论系统带有自动识别垃圾评论功能,请写一些有意义的评论,谢谢!