判断文件或目录是否存在的几种方式

1. Linux系统,c语言环境

#include <unistd.h>

int access(const char *pathname, int mode);

参数说明:

pathname --文件或文件夹的路径

mode --模式

R_OK 只判断是否有读权限

W_OK 只判断是否有写权限

X_OK 判断是否有执行权限

F_OK 只判断是否存在

返回值--如果指定的存取方式有效,则函数返回0,否则函数返回-1

上代码:

#include <iostream>
#include <string>
#include <unistd.h>

int main()
{
    std::string path("/root/user/work/test.cpp");
    int ret = access(path.c_str(), F_OK);
    if(ret != 0)
    {
        std::cout << "文件不存在" << std::endl;
    }
    return 0;
}

2.Linux系统,c++语言环境,需要c++17

头文件#include <experimental/filesystem>

exists函数源码


  inline bool
  exists(file_status __s) noexcept
  { return status_known(__s) && __s.type() != file_type::not_found; }

  inline bool
  exists(const path& __p)
  { return exists(status(__p)); }

  inline bool
  exists(const path& __p, error_code& __ec) noexcept
  {
    auto __s = status(__p, __ec);
    if (status_known(__s))
      {
	__ec.clear();
	return __s.type() != file_type::not_found;
      }
    return false;
  }

参数:

_s-file status to check
_p-path to examine
_ec-out-parameter for error reporting in the non-throwing overload

返回值:

true -- if the given path or file status corresponds to an existing file or directory

false -- otherwise.

代码:

#include <iostream>
#include <string>
#include <experimental/filesystem>

int main()
{
    std::string path("/root/user/work/test.cpp");
    int ret = std::experimental::filesystem::exists(path);
    if(ret != true)
    {
        std::cout << "文件不存在" << std::endl;
    }
    return 0;
}

3.boost,C++

boost::filesystem::exists(file_path)

代码

#include<boost/filesystem.hpp>
{
    boost::filesystem::path file_path = "file";
    if(boost::filesystem::exists(file_path)) { //判断路径是否存在
        std::cout << "文件存在" << std::endl;
    } 
    else {
        boost::filesystem::create_directory(file_path);  //文件夹不存在则创建一个
        boost::filesystem::create_directories(file_path);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

phoeton

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值