Linux c++ 判断文件夹是否存在及创建文件夹

Linux c++ 判断文件夹是否存在及创建文件夹

判断文件夹是否存在

#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <iostream>

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); 
}

经过测试,isFileExists_stat耗时最短。

参考:
https://zhuanlan.zhihu.com/p/180501394

创建文件夹

#include <iostream>
#include <string>
#include <sys/stat.h>
#include <errno.h>

namespace light
{
    int mkpath(std::string s, mode_t mode = 0755)
    {
        size_t pre = 0, pos;
        std::string dir;
        int mdret;

        if (s[s.size() - 1] != '/')
        {
            // force trailing / so we can handle everything in loop
            s += '/';
        }

        while ((pos = s.find_first_of('/', pre)) != std::string::npos)
        {
            dir = s.substr(0, pos++);
            pre = pos;
            if (dir.size() == 0)
                continue; // if leading / first time is 0 length
            if ((mdret = ::mkdir(dir.c_str(), mode)) && errno != EEXIST)
            {
                return mdret;
            }
        }
        return mdret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值