Linux/Unix 判断一个路径是目录还是文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lilil371324/article/details/51968932
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
/**
 * 判断路径是目录还是文件
 */
void pathType(const char* filename)
{
    struct stat info;
    int r=stat(filename, &info);
    printf("%s  ", filename);
    if(r==0)
    {
        if(S_ISDIR(info.st_mode)) printf("folder\n");
        else printf("file\n");
    }else
    {
        if( errno==ENOENT) printf("nonexistent\n");
        else printf("error");
    }
}

int main()
{
    pathType("/etcc"); // nonexistent
    pathType("/etc/host");    // file
    pathType("/etc");       // folder
    return 0;
}

结果如图所示:
这里写图片描述

struct stat详解链接。

猜你喜欢

转载自blog.csdn.net/lilil371324/article/details/51968932