Linux下的C++程序:判断目录/文件是否存在

本文中写了两个函数:

1)int IsFileExist(const char* path)

用于检查一个目录是否存在 -1:存在 0:不存在

2)int IsFileExist(const char* path)

用于检查文件(所有类型,包括目录类型)是否存在 -1:存在 0:不存在

如果不存在,可以用以下两种方式打印错误信息:

1)fprintf(stderr, "ERROR: %s\n", strerror(errno));

2)perror("ERROR");

程序代码:

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

#include <string.h>
#include <errno.h>

//检查目录是否存在
//-1:存在 0:不存在
int IsFolderExist(const char* path)
{
    DIR *dp;
    if ((dp = opendir(path)) == NULL)
    {
        return 0;
    }

    closedir(dp);
    return -1;
}

//检查文件(所有类型)是否存在
//-1:存在 0:不存在
int IsFileExist(const char* path)
{
    return !access(path, F_OK);
}

//
void Display(const char *path)
{
    if (IsFolderExist(path))
    {
        printf("Folder [%s] Exist!\n", path);
    }
    else
    {
        printf("Folder [%s]\n", path);
        //捕获errno方法1: fprintf
        fprintf(stderr, "ERROR: %s\n", strerror(errno));
    }

    if(IsFileExist(path))
    {
        printf("File [%s] Exist!\n", path);
    }
    else
    {
        printf("File [%s]\n", path);
        //捕获error方法2: perror
        perror("ERROR");
    }
}

int main()
{
    Display("/home/oracle/Documents");     //Current Folder
    Display("/home/12345edcba");           //Folder Not Exist
    Display("/home/oracle/Documents/a.c"); //Existing File

    return 0;    
}

运行截图:

191708_nOIm_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/338232

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值