C++ 50行代码实现Linux ls -l 命令

说明:此代码并不是实现完整的 ls 命令

// filename:myls_l.cpp
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <string>

int main(int argc, char *argv[])
{
	 using std::cout;
	 using std::endl;
	 using std::string;
	 struct stat st;
	 struct passwd *wd;
	 struct group *gp;
	 string tm;
	 int ret = stat(argv[1], &st);
	 if(ret == -1) { cout << "open error" << endl; return -1; }
	 if(S_ISREG(st.st_mode))   	cout << "-";
	 else if(S_ISDIR(st.st_mode))  	cout << "d";
	 else if(S_ISCHR(st.st_mode))   cout << "c";
	 else if(S_ISBLK(st.st_mode))   cout << "b";
	 else if(S_ISLNK(st.st_mode))   cout << "l";
	 else if(S_ISFIFO(st.st_mode))  cout << "f";
	 else if(S_ISSOCK(st.st_mode))  cout << "s";
	 if (st.st_mode & S_IRUSR)  	cout << "r";
	 else       			cout << "-";
	 if (st.st_mode & S_IWUSR)  	cout << "w";
	 else       			cout << "-";
	 if (st.st_mode & S_IXUSR)  	cout << "x";
	 else       			cout << "-";
	 if (st.st_mode & S_IRGRP)  	cout << "r";
	 else       			cout << "-";
	 if (st.st_mode & S_IWGRP)  	cout << "w";
	 else       			cout << "-";
	 if (st.st_mode & S_IXGRP)  	cout << "x";
	 else       			cout << "-";
	 if (st.st_mode & S_IROTH)  	cout << "r";
	 else       			cout << "-";
	 if (st.st_mode & S_IWOTH)  	cout << "w";
	 else       			cout << "-";
	 if (st.st_mode & S_IXOTH)  	cout << "x";
	 else       			cout << "-";
	 cout << " " << st.st_nlink;
	 wd = getpwuid(st.st_uid);
	 cout << " " << wd->pw_name;
	 gp = getgrgid(st.st_gid);
	 cout << " " << gp->gr_name;
	 cout << " " << st.st_size;
	 tm = ctime(&st.st_mtime);
	 cout << " " << tm.substr(4, 12);
	 cout << " " << argv[1] << endl;
	 return 0;
}
	

调用方法:

$ g++ -o myls_l myls_l.cpp
$ ./myls_l myls_l.cpp
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值