【操作系统】实验6-仿写Linux下的ls-s命令(转载)

这篇博客详细介绍了如何使用C++编程语言仿写Linux系统下的ls和ls-l命令。作者通过包含头文件如<iostream>,<dirent.h>等,并使用stat结构体和getpwuid、getgrgid函数获取文件信息,实现了列出目录内容及详细信息的功能。代码中包含了读取目录、过滤‘.’开头的隐藏文件、显示文件权限、所有者、组、大小和修改时间等操作。
摘要由CSDN通过智能技术生成

【操作系统】实验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

(如有侵权,请联系我删除)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值