Printing file permissions like 'ls -l' using stat(2) in C

后端 未结 3 1756
梦谈多话
梦谈多话 2021-02-01 20:53

I am trying to write a small C program that emulates the unix command ls -l. To do so, I am using the stat(2) syscall and have ran into a small hi

3条回答
  •  萌比男神i
    2021-02-01 21:34

    I don't like the if/ else if syntax.

    I prefer use the switch statement. After struggling a bit I found the way we can do it using different macros, for example:

    S_ISCHR (mode)
    

    Is equivalent to:

    ((mode & S_IFMT) == S_IFCHR)
    

    This allows us to build a switch statement like this:

    char f_type(mode_t mode)
    {
        char c;
    
        switch (mode & S_IFMT)
        {
        case S_IFBLK:
            c = 'b';
            break;
        case S_IFCHR:
            c = 'c';
            break;
        case S_IFDIR:
            c = 'd';
            break;
        case S_IFIFO:
            c = 'p';
            break;
        case S_IFLNK:
            c = 'l';
            break;
        case S_IFREG:
            c = '-';
            break;
        case S_IFSOCK:
            c = 's';
            break;
        default:
            c = '?';
            break;
        }
        return (c);
    }
    

    Which in my opinion it's a bit more elegant than the if/else if approach.

提交回复
热议问题