初级版linux中 ls 命令实现

直接放代码:

#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命令:
在这里插入图片描述在这里插入图片描述

我的程序结果:
在这里插入图片描述
在这里插入图片描述

整体功能还差得远,纯属娱乐

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值