直接放代码:
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <string.h>
#include <sys/stat.h>
#include <cmath>
#include <iostream>
char *getFileAcessPermission(mode_t mode) {
char *buf = (char *)malloc(11 * sizeof(char));
strcpy(buf, "----------");
// 还有其他类型,不一一加了
if (S_ISDIR(mode)) buf[0] = 'd';
if (S_ISLNK(mode)) buf[0] = 'l';
if (S_IRUSR & mode) buf[1] = 'r';
if (S_IWUSR & mode) buf[2] = 'w';
if (S_IXUSR & mode) buf[3] = 'x';
if (S_IRGRP & mode) buf[4] = 'r';
if (S_IWGRP & mode) buf[5] = 'w';
if (S_IXGRP & mode) buf[6] = 'x';
if (S_IROTH & mode) buf[7] = 'r';
if (S_IWOTH & mode) buf[8] = 'w';
if (S_IXOTH & mode) buf[9] = 'x';
return buf;
}
void travel(char *path) {
auto dir = opendir(path);
if (dir == NULL) {
std::cerr << "open dir fail" << std::endl;
return;
}
struct dirent *dirp;
struct psswd *passp;
struct group *grpp;
char timebuf[32];
auto n = strlen(path);
auto fullpath = (char *)malloc(n + NAME_MAX + 2);
strcpy(fullpath, path);
fullpath[n++] = '/';
while ((dirp = readdir(dir)) != NULL) {
struct stat stat_buf;
strcpy(&fullpath[n], dirp->d_name);
if (lstat(fullpath, &stat_buf) != 0) {
std::cerr << "lstat fail dirname:" << dirp->d_name << std::endl;
continue;
}
auto passptr = getpwuid(stat_buf.st_uid);
if (passptr == NULL) continue;
auto groupptr = getgrgid(stat_buf.st_gid);
if (groupptr == NULL) return;
auto permission = getFileAcessPermission(stat_buf.st_mode);
auto tmp = localtime(&stat_buf.st_mtim.tv_sec);
strftime(timebuf, 32, "%b %d %R", tmp);
printf("%s %s %s %5d %s %s \n", permission, passptr->pw_name,
groupptr->gr_name, stat_buf.st_size, timebuf, dirp->d_name);
free(permission);
}
}
int main(int argc, char *argv[]) {
if (argc < 2) return 0;
travel(argv[1]);
return 0;
}
测试结果:
系统ls命令:
我的程序结果:
整体功能还差得远,纯属娱乐