Linux ubuntu环境下用C程序实现ls -l命令功能

                       ubuntu下 ls -l 命令的结果:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
char gettype(mode_t st_mode)
{
  switch(S_IFMT & st_mode)
  {

    case S_IFSOCK:return 's';
    case S_IFLNK:return 'l';
    case S_IFREG:return '-';
    case S_IFBLK:return 'b';
    case S_IFDIR:return 'd';
    case S_IFCHR:return 'c';
    case S_IFIFO:return 'p';
  }

}
char* getmode(mode_t st_mode)
{
  static char mode[10]={0};
  int i=9;
  while(i--)
  {
    if(st_mode & (1<<i))
    {
      //rwxr-xr-x
      switch(i%3)
      {
        case 0:
          mode[8-i]='x';break;
        case 1:
          mode[8-i]='w';break;
        case 2:
          mode[8-i]='r';break;
      }
    }
    else {
      mode[8-i]='-';
    }
  }
  return mode;
}
int main(int argc, char const* argv[])
{
  struct tm *times;
  struct stat sb;
  struct dirent *pdir;
  DIR *dirp=opendir(argv[1]);
  if(dirp==NULL)
  {
    perror("opendir");
    exit(1);
  }
  while(pdir=readdir(dirp))
  {
    if((strncmp(pdir->d_name,".",1)==0) || (strcmp(pdir->d_name,"..")==0))
      continue;
    stat(pdir->d_name,&sb);
    times=localtime(&sb.st_mtime);
    printf("%c%s %lu %s %s  %lu  %d月  %d  %d:%d  %s\n",gettype(sb.st_mode),getmode(sb.st_mode),sb.st_nlink,getpwuid(sb.st_uid)->pw_name,getgrgid(sb.st_gid)->gr_name,sb.st_size,times->tm_mon+1,times->tm_mday,times->tm_hour,times->tm_min,pdir->d_name);
  }
  return 0;
}

代码运行:./a.out +文件路径

stat函数参考此链接:https://blog.csdn.net/qq_40839779/article/details/82789217

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值