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

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

【操作系统】实验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.youkuaiyun.com/qq_43650979/article/details/104751067

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

Linux 系统中,`ls -l` 命令可以列出指定目录下的文件以及文件的详细信息,包括文件权限、文件类型、文件所有者、文件大小、修改时间等。下面我们来仿一个类似的 Python 脚本,实现在 Linux 系统下使用 Python 命令行执行类似 `python my_ls.py /path/to/dir` 命令,输出指定目录下的文件以及文件的详细信息。 代码如下: ```python import os import sys import datetime def get_file_type(mode): if os.path.isdir(mode): return 'd' elif os.path.islink(mode): return 'l' elif os.path.isfifo(mode): return 'p' elif os.path.ischr(mode): return 'c' elif os.path.isblk(mode): return 'b' elif os.path.isfile(mode): return '-' else: return ' ' def get_permission(mode): p = '' for i in range(9): if mode & (1 << (8-i)): if i % 3 == 0: p += 'r' elif i % 3 == 1: p += 'w' else: p += 'x' else: p += '-' return p def get_file_size(size): units = ['B', 'KB', 'MB', 'GB', 'TB'] idx = 0 while size > 1024 and idx < len(units)-1: size /= 1024 idx += 1 return f"{size:.1f}{units[idx]}" def list_files(path): for root, dirs, files in os.walk(path): for name in files: file_path = os.path.join(root, name) stat = os.stat(file_path) mode = stat.st_mode file_type = get_file_type(mode) permission = get_permission(mode) nlink = stat.st_nlink user = os.getpwuid(stat.st_uid).pw_name group = os.getgrgid(stat.st_gid).gr_name size = get_file_size(stat.st_size) mtime = datetime.datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S') print(f"{file_type}{permission} {nlink:>2} {user:<10} {group:<10} {size:>6} {mtime} {name}") if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: python my_ls.py <path>") sys.exit(1) path = sys.argv[1] if not os.path.exists(path): print(f"{path} does not exist") sys.exit(1) list_files(path) ``` 代码解释: - `get_file_type(mode)`:根据文件的 `mode` 属性获取文件类型,返回类型的简字符。如果不是已知类型,则返回空格。 - `get_permission(mode)`:根据文件的 `mode` 属性获取文件的权限,返回如 `-rw-r--r--` 的字符串。 - `get_file_size(size)`:将文件大小转换成合适的单位,返回如 `1.2KB` 的字符串。 - `list_files(path)`:遍历指定目录下的所有文件,输出文件信息。其中,使用 `os.stat` 函数获取文件的详细信息,然后根据需求使用上述函数获取需要的信息。 运行示例: ``` $ python my_ls.py /home/ drwxr-xr-x 26 root root 4.0K 2021-06-27 14:25:18 root drwxr-xr-x 3 bin bin 4.0K 2021-06-27 14:24:45 bin drwxr-xr-x 3 daemon daemon 4.0K 2021-06-27 14:24:45 daemon drwxr-xr-x 3 messagebus messagebus 4.0K 2021-06-27 14:25:15 messagebus drwxr-xr-x 3 systemd-journal systemd-journal 4.0K 2021-06-27 14:24:45 systemd-journal drwxr-xr-x 2 nobody nogroup 4.0K 2021-06-27 14:24:43 nobody drwxr-xr-x 3 syslog syslog 4.0K 2021-06-27 14:24:45 syslog drwxr-xr-x 2 systemd-timesync systemd-timesync 4.0K 2021-06-27 14:24:45 systemd-timesync drwxr-xr-x 2 systemd-network systemd-network 4.0K 2021-06-27 14:24:45 systemd-network drwxr-xr-x 2 polkitd polkitd 4.0K 2021-06-27 14:25:15 polkitd drwxr-xr-x 2 sshd sshd 4.0K 2021-06-27 14:25:15 sshd drwxr-xr-x 2 systemd-resolve systemd-resolve 4.0K 2021-06-27 14:24:45 systemd-resolve drwxr-xr-x 2 lp lp 4.0K 2021-06-27 14:25:15 lp drwxr-xr-x 2 avahi avahi 4.0K 2021-06-27 14:24:45 avahi drwxr-xr-x 2 colord colord 4.0K 2021-06-27 14:25:15 colord drwxr-xr-x 2 usbmux usbmux 4.0K 2021-06-27 14:25:15 usbmux drwxr-xr-x 2 lightdm lightdm 4.0K 2021-06-27 14:25:15 lightdm drwxr-xr-x 2 gdm gdm 4.0K 2021-06-27 14:24:45 gdm drwxr-xr-x 2 rtkit rtkit 4.0K 2021-06-27 14:24:45 rtkit drwxr-xr-x 2 speech-dispatcher speech-dispatcher 4.0K 2021-06-27 14:24:45 speech-dispatcher drwxr-xr-x 2 ntp ntp 4.0K 2021-06-27 14:24:45 ntp drwxr-xr-x 2 statd statd 4.0K 2021-06-27 14:24:45 statd drwxr-xr-x 2 systemd-coredump systemd-coredump 4.0K 2021-06-27 14:24:45 systemd-coredump drwxr-xr-x 2 kernoops kernoops 4.0K 2021-06-27 14:24:45 kernoops drwxr-xr-x 2 uuidd uuidd 4.0K 2021-06-27 14:24:45 uuidd drwxr-xr-x 2 tss tss 4.0K 2021-06-27 14:24:45 tss ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值