[C++][转载]C++判断文件是否存在

1. 使用boost判断文件是否存在

std::string file_path = "file_name";
if (!boost::filesystem::exists(file_path))
  {
    std::cout << "not exist file" << std::endl;
  }

使用boost时需要包含:

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/typeof/typeof.hpp>

2. 使用C++标准库判断

  1. #include <fstream> --> 使用ifstream打开文件流,成功则存在,失败则不存在;
  2. #include <stdio.h> --> 以fopen读方式打开文件,成功则存在,否则不存在;
  3. #include <unistd.h> --> 使用access函数获取文件状态,成功则存在,否则不存在
  4. #include <sys/stat.h> --> 使用stat函数获取文件状态,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <iostream>

using namespace std;
bool isFileExists_ifstream(string& name) {
    ifstream f(name.c_str());
    return f.good();
}
bool isFileExists_fopen(string& name) {
    if (FILE *file = fopen(name.c_str(), "r")) {
        fclose(file);
        return true;
    } else {
        return false;
    }   
}
bool isFileExists_access(string& name) {
    return (access(name.c_str(), F_OK ) != -1 );
}
bool isFileExists_stat(string& name) {
  struct stat buffer;   
  return (stat(name.c_str(), &buffer) == 0); 
}

 其中acces函数参数意义如下:

/* Values for the second argument to access.
   These may be OR'd together.  */
#define	R_OK	4		/* Test for read permission.  */
#define	W_OK	2		/* Test for write permission.  */
#define	X_OK	1		/* Test for execute permission.  */
#define	F_OK	0		/* Test for existence.  */

/* Test for access to NAME using the real UID and real GID.  */
extern int access (const char *__name, int __type) __THROW __nonnull ((1));

传入的两个变量分别是文件夹的路径,以及需要查询的权限,6代表读写权限,0代表存在与否。

std::string folderpath = "/<the_folder_path>";
if(access(folderpath.c_str(), 0)){
     std::cout<<"folder does not exist! Will create a new one!" <<std::endl;
        }

转载自:C++判断文件是否存在的方法汇总 - 万丈高楼平地起 - 博客园

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FL1623863129

你的打赏是我写文章最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值