c语言判断是文件还是文件夹,软链接,硬链接

摘自:文心一言

在C语言中,可以使用stat()函数来判断一个路径对应的是文件、文件夹或者其他类型。

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
 
int main() {
    char path[] = "/path/to/file_or_folder"; // 要判断的路径
    
    struct stat fileInfo;
    if (lstat(path, &fileInfo) == -1) {
        perror("Error");
        return 1;
    }
    
    if (S_ISREG(fileInfo.st_mode)) {
        printf("%s is a regular file.\n", path);
    } else if (S_ISDIR(fileInfo.st_mode)) {
        printf("%s is a directory.\n", path);
    } else if (S_ISLNK(fileInfo.st_mode)) {
        printf("%s is a symbolic link.\n", path);
    } else if (S_ISBLK(fileInfo.st_mode)) {
        printf("%s is a block device.\n", path);
    } else if (S_ISCHR(fileInfo.st_mode)) {
        printf("%s is a character device.\n", path);
    } else if (S_ISFIFO(fileInfo.st_mode)) {
        printf("%s is a FIFO pipe.\n", path);
    } else if (S_ISSOCK(fileInfo.st_mode)) {
        printf("%s is a socket.\n", path);
    } else {
        printf("%s has an unknown type.\n", path);
    }
    
    return 0;
}

 

posted @ 2024-02-05 10:39  LiuYanYGZ  阅读(253)  评论(0编辑  收藏  举报