c++文件夹存在判断

12 篇文章 0 订阅

(1)Win API

bool CheckFolderExist(const string &strPath)
{
    WIN32_FIND_DATA wfd;
    bool rValue = false;
    HANDLE hFind = FindFirstFile(strPath.c_str(), &wfd);
    if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
    {
        rValue = true;  
    }
    FindClose(hFind);
    return rValue;
}

 

(2)Win SHell

PathFileExists("yourfile") 

 

使用时加上:#include "Shlwapi.h" #pragma comment(lib,"Shlwapi.lib")

 

 

(3)Win API

bool FileExists(LPCTSTR lpszFileName, bool bIsDirCheck)
{
DWORD dwAttributes = GetFileAttributes(lpszFileName);
    if(dwAttributes == 0xFFFFFFFF)
{
        return false;
}

if((dwAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
{
   return bIsDirCheck;
}
else
{
   return !bIsDirCheck;
}
}

 

(4)使用boost的filesystem类库的exists函数

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>

int GetFilePath(std::string &strFilePath)
{
    string strPath;
    int nRes = 0;

    //指定路径           
    strPath = "D:/myTest/Test1/Test2";
    namespace fs = boost::filesystem;

    //路径的可移植
    fs::path full_path( fs::initial_path() );
    full_path = fs::system_complete( fs::path(strPath, fs::native ) );
    //判断各级子目录是否存在,不存在则需要创建
    if ( !fs::exists( full_path ) )
    {
        // 创建多层子目录
        bool bRet = fs::create_directories(full_path);
        if (false == bRet)
        {
            return -1;
        }

    }
    strFilePath = full_path.native_directory_string();

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值