stat函数获取文件权限和类型

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv){
    
    
    struct stat sbuf;
    int r = stat(argv[1], &sbuf);
    if (r == -1){
    
    
        perror("stat error");
        exit(1);
    }
    if (sbuf.st_mode & S_IRUSR)printf("User Can Read!\n");
    if (sbuf.st_mode & S_IWUSR)printf("User Can Write!\n");
    if (sbuf.st_mode & S_IXUSR)printf("User Can Execute!\n");
    // type:
    if (S_ISDIR(sbuf.st_mode))printf("dir\n");
    else if (S_ISFIFO(sbuf.st_mode))printf("pipe\n");
    else if (S_ISREG(sbuf.st_mode))printf("regular\n");
    else printf("unknown");
    return 0;
}

如果文件类型是链接文件,stat会穿透链接文件,直接获取源文件的类型等信息。lstat函数不会穿透

猜你喜欢

转载自blog.csdn.net/weixin_43701790/article/details/121897433