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

后端 未结 3 1706
梦谈多话
梦谈多话 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条回答
  •  抹茶落季
    2021-02-01 21:46

    example from google

    #include 
    #include 
    #include 
    #include 
    
    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

提交回复
热议问题