詳解C++ 創(chuàng)建文件夾的四種方式
在開頭不得不吐槽一下,我要的是簡單明了的創(chuàng)建文件夾的方式,看得那些文章給的都是復(fù)雜吧唧的一大坨代碼,不仔細(xì)看鬼知道寫的是啥。因此,為了方便以后自己閱讀,這里自己寫一下 C++ 創(chuàng)建文件夾的四種方式:
貌似都是 Windows 的
提前說明:從參數(shù)角度上看,其實都應(yīng)該使用 char*,但是為了方便這里使用的都是 string。在 SO 上找到一個方式把 string 轉(zhuǎn)成 char*,就是調(diào)用 string 的 c_str() 函數(shù)。
本文示例都是在 E:\database 路徑下創(chuàng)建一個叫做 testFolder 的文件夾。
使用 system() 調(diào)用 dos 命令
#include <iostream>
using namespace std;
int main()
{
string folderPath = "E:\\database\\testFolder";
string command;
command = "mkdir -p " + folderPath;
system(command.c_str());
return 0;
}
使用頭文件 direct.h 中的 access 和 mkdir 函數(shù)
關(guān)于 direct.h 我覺得 維基百科 上介紹的不錯
#include <direct.h>
#include <iostream>
using namespace std;
int main()
{
string folderPath = "E:\\database\\testFolder";
if (0 != access(folderPath.c_str(), 0))
{
// if this folder not exist, create a new one.
mkdir(folderPath.c_str()); // 返回 0 表示創(chuàng)建成功,-1 表示失敗
//換成 ::_mkdir ::_access 也行,不知道什么意思
}
return 0;
}
調(diào)用 Windows API 函數(shù)
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
string folderPath = "E:\\database\\testFolder";
if (!GetFileAttributesA(folderPath.c_str()) & FILE_ATTRIBUTE_DIRECTORY) {
bool flag = CreateDirectory(folderPath.c_str(), NULL);
// flag 為 true 說明創(chuàng)建成功
} else {
cout<<"Directory already exists."<<endl;
}
return 0;
}
調(diào)用 MFC 封裝好的接口函數(shù)
不推薦此方法,出錯的話會有點(diǎn)麻煩。
#include <iostream>
#include <shlwapi.h>
using namespace std;
int main()
{
string folderPath = "E:\\database\\testFolder";
if (!PathIsDirectory(folderPath.c_str())) // 是否有重名文件夾
{
::CreateDirectory(folderPath.c_str(), 0);
}
return 0;
}
如果你出現(xiàn)了錯誤 undefined reference to imp__PathIsDirectory @ 4,可以參考 undefined reference to imp PathIsDirectory
下面的方法是基于你詳細(xì)閱讀完上述鏈接后的前提下給出的
說我在 CodeBlocks 下解決該問題的方法:
第一步:在項目上右擊,選擇 Build Options

第二步: 在 Linker Settings 里添加 libshlwapi.a 文件

到此這篇關(guān)于C++ 創(chuàng)建文件夾的四種方式的文章就介紹到這了,更多相關(guān)C++ 創(chuàng)建文件夾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于C語言程序的內(nèi)存分配的入門知識學(xué)習(xí)
這篇文章主要介紹了關(guān)于C語言程序的內(nèi)存分配的入門知識學(xué)習(xí),特別強(qiáng)調(diào)了堆與棧的內(nèi)存空間申請比較,需要的朋友可以參考下2015-12-12
如何使用C語言實現(xiàn)細(xì)菌的繁殖與擴(kuò)散
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)細(xì)菌的繁殖與擴(kuò)散,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11

