使用函数dirent,stat,等函数实现ls -l 的功能

该代码示例演示了如何使用C语言结合系统调用,如`readdir`、`closedir`、`stat`和`getpwuid`,遍历指定目录下的文件并打印其类型、权限、所有者和修改时间等信息。通过`S_ISxxx`宏判断文件类型,包括常规文件、目录、字符设备、块设备、管道、套接字和符号链接,并展示文件的读写执行权限。
摘要由CSDN通过智能技术生成
  1. 了解所需要使用的函数,使用shell命令 man 来查看它们的使用方法
  2. struct dirent *readdir(DIR *dirp);int closedir(DIR *dirp);int stat(const char *path, struct stat *buf);struct passwd *getpwuid(uid_t uid);
  3. 结构体:
  4. struct dirent{xxx};

struct stat{xxx}

  1. 文件类型
    {
        常规文件:S_ISREG     '-'
        目录:S_ISDIR         'd'
        字符设备:S_ISCHR     'c'
        块设备:S_ISBLK     'b'
        管道:S_ISFIFO         'p'
        套接字:S_ISSOCK     's'
        符号链接:S_ISLNK     'l'
    }
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <unistd.h>
#include <pwd.h>
int main(int argc, char *argv[])
{ 
    DIR *p = opendir(argv[1]);
    while(1)
    {
        struct stat mybuf;
        struct dirent *q = readdir(p);
        if(q == NULL)
            return -1;
        else if(strncmp(q->d_name,".",1)==0)
            continue;
        stat(q->d_name,&mybuf);
        if(S_ISREG(mybuf.st_mode))
            printf("-");
        if(S_ISDIR(mybuf.st_mode))
            printf("d");
        if(S_ISCHR(mybuf.st_mode))
            printf("c");
        if(S_ISBLK(mybuf.st_mode))
            printf("b");
        if(S_ISFIFO(mybuf.st_mode))
            printf("p");
        if(S_ISSOCK(mybuf.st_mode))
            printf("s");
        if(S_ISLNK(mybuf.st_mode))
            printf("l");
        printf("%c", (mybuf.st_mode & (0x1<<8) )?'r':'-');
        printf("%c", (mybuf.st_mode & (0x1<<7) )?'w':'-');
        printf("%c", (mybuf.st_mode & (0x1<<6) )?'x':'-');
        printf("%c", (mybuf.st_mode & (0x1<<5) )?'r':'-');
        printf("%c", (mybuf.st_mode & (0x1<<4) )?'w':'-');
        printf("%c", (mybuf.st_mode & (0x1<<3) )?'x':'-');
        printf("%c", (mybuf.st_mode & (0x1<<2) )?'r':'-');
        printf("%c", (mybuf.st_mode & (0x1<<1) )?'w':'-');
        printf("%c ", (mybuf.st_mode & (0x1) )?'x':'-');
        printf("%ld ", mybuf.st_nlink);
        struct passwd *w = getpwuid(mybuf.st_uid);
	    printf("%s ", w->pw_name);
        struct passwd *m = getpwuid(mybuf.st_gid);
	    printf("%s ", m->pw_name);
        printf("%ld ", mybuf.st_size);
        struct tm *k = localtime(&mybuf.st_mtime);
	    printf("%d月 ", k->tm_mon+1);
	    printf("%d  ", k->tm_mday);
	    printf("%d:", k->tm_hour);
	    printf("%d ", k->tm_min);
        printf("%s\n",q->d_name);
    }
    return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下雨的路口

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值