c++ 判斷檔案夾是否存在

來源:互聯網
上載者:User

(1)

//目錄是否存在的檢查:
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)PathFileExists("yourfile") 但是使用時候需要 #include "Shlwapi.h"

 

(3)

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.