1. 程式人生 > >C++建立資料夾的方式

C++建立資料夾的方式

提前說明:從引數角度上看,其實都應該使用 char*,但是為了方便這裡使用的都是 string。在 sof 上找到一個方式把 string 轉成 char*,就是呼叫 string 的函式 c_str()。

文字都是在 E:\database 路徑下建立一個叫做 testFolder 的資料夾。給出的資料夾路徑的方式是基於我的需要,不是最簡單的。

一、使用 system() 呼叫 dos 命令
#include <iostream>
using namespace std;

int main()
{
    string defaultPath = "E:\\database";
    string folderPath = defaultPath + "\\testFolder"; 

    string command;
    command = "mkdir -p " + folderPath;  
    system(command.c_str());

    return 0;
}

二、使用標頭檔案 direct.h 中的 access 和 mkdir 函式
關於 direct.h 我覺得 維基百科 上介紹的不錯

#include <iostream>
#include <direct.h>
using namespace std;

int main()
{
    string defaultPath = "E:\\database";
    string folderPath = defaultPath + "\\testFolder";

    if (0 != access(folderPath.c_str(), 0))
    {
        // if this folder not exist, create a new one.
        mkdir(folderPath.c_str());
        //換成 ::_mkdir  ::_access 也行,不知道什麼意思
    }

    return 0;
}

三、呼叫 Windows API 函式
#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    string defaultPath = "E:\\database";
    string folderPath = defaultPath + "\\testFolder";

    bool flag = CreateDirectory(folderPath.c_str(), NULL);
    // flag 為 true 說明建立成功

    return 0;
}

四、呼叫 MFC 封裝好的介面函式
不推薦此方法,出錯的話會有點麻煩。

#include <iostream>
#include <shlwapi.h>
using namespace std;

int main()
{
    string defaultPath = "E:\\database";
    string folderPath = defaultPath + "\\testFolder";

    if (!PathIsDirectory(folderPath.c_str()))  // 是否有重名資料夾
    {
        ::CreateDirectory(folderPath.c_str(), 0);
    }

    return 0;
}

如果你出現了錯誤 undefined reference to imp__PathIsDirectory @ 4,可以參考 undefined reference to imp PathIsDirectory
下面的方法是基於你詳細閱讀完上述連結後的前提下給出的

說我在 CodeBlocks 下解決該問題的方法:
第一步:在專案上右擊,選擇 Build Options


第二步: 在 Linker Settings 裡新增 libshlwapi.a 檔案

--------------------- 

原文:https://blog.csdn.net/sinat_41104353/article/details/83149441