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

cheezone picture cheezone · Apr 25, 2012 · Viewed 69.3k times · Source

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 hiccup writing the permissions. I have a mode_t variable which holds the file permissions from st_mode, and it wouldn't be hard to parse that value into s string representation, but I was just wondering if there is a better way to be doing it than that.

Answer

askovpen picture askovpen · Apr 25, 2012

example from google

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

int main(int argc, char **argv)
{
    if(argc != 2)    
        return 1;

    struct stat fileStat;
    if(stat(argv[1], &fileStat) < 0)    
        return 1;

    printf("Information for %s\n", argv[1]);
    printf("---------------------------\n");
    printf("File Size: \t\t%d bytes\n", fileStat.st_size);
    printf("Number of Links: \t%d\n", fileStat.st_nlink);
    printf("File inode: \t\t%d\n", fileStat.st_ino);

    printf("File Permissions: \t");
    printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
    printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
    printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
    printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
    printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
    printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
    printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
    printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
    printf( (fileStat.st_mode & S_IWOTH) ? "w" : "-");
    printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
    printf("\n\n");

    printf("The file %s a symbolic link\n", (S_ISLNK(fileStat.st_mode)) ? "is" : "is not");

    return 0;
}

result:

Information for 2.c
---------------------------
File Size:              1223 bytes
Number of Links:        1
File inode:             39977236
File Permissions:       -rw-r--r--

The file is not a symbolic link