关于POSIX定义的宏S_ISLINK(),S_ISREG()的使用

摘自:https://forum.ubuntu.org.cn/viewtopic.php?t=380854

我在学习linux C系统编程,书上有个源代码可以实现自己的ls命令,不过在查错的过程中这个问题卡了我很久

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <limits.h>
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <errno.h>

#define    PARAM_NONE    0
#define    PARAM_A        1
#define    PARAM_L         2
#define    MAXROWLEN    80

int            g_leave_len=MAXROWLEN;
int            g_maxlen;

void my_error(const char* err_string,int line)
{
    fprintf(stderr,"line:%d",line);
    perror(err_string);
    exit(1);
}

void display_attribute(struct stat buf,char* name)
{
    char buf_time[32];
    struct passwd *psd;
    struct group *grp;

    if(S_ISLINK(buf.st_mode))//编译器报错,找不到S_ISLINK的定义
        printf("l");
    else if(S_ISREG(buf.st_mode))
        printf("-");
    else if(S_ISDIR(buf.st_mode))
        printf("d");
    else if(S_ISCHR(buf.st_mode))
        printf("c");
    else if(S_ISBLK(buf.st_mode))
        printf("b");
    else if(S_ISFIFO(buf.st_mode))
        printf("f");
    else if(S_ISSOCK(buf.st_mode))
        printf("s");

    if(buf.st_mode&S_IRUSR)
        printf("r");
    else
        printf("-");

    if(buf.st_mode&S_IWUSR)
        printf("w");
    else
        printf("-");

    if(buf.st_mode&S_IXUSR)
        printf("x");
    else
        printf("-");

    if(buf.st_mode&S_IRGRP)
        printf("r");
    else
        printf("-");

    if(buf.st_mode&S_IWGRP)
        printf("w");
    else
        printf("-");

    if(buf.st_mode&S_IXGRP)
        printf("x");
    else
        printf("-");

    if(buf.st_mode&S_IROTH)
        printf("r");
    else
        printf("-");

    if(buf.st_mode&S_IWOTH)
        printf("w");
    else
        printf("-");

    if(buf.st_mode&S_IXOTH)
        printf("x");
    else
        printf("-");

    printf("\t\t");

    psd=getpwuid(buf.st_uid);
    grp=getgrgid(buf.st_gid);
    printf("%4d",buf.st_nlink);
    printf("%-8s",psd->pw_name);
    printf("%-8s",grp->gr_name);

    printf("%6d",(int)buf.st_size);
    strcpy(buf_time,ctime(&buf.st_mtime));
    buf_time[strlen(buf_time)-1]='\0';
    printf("\t%s",buf_time);
}
复制代码

 

posted @   LiuYanYGZ  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2022-02-05 TS型网页视频下载方法____________________m3u8视频在线提取工具-单线程太慢
点击右上角即可分享
微信分享提示