这篇文章给大家分享的是C++中实现创建文件夹的方法。小编觉得挺实用的,因此分享给大家做个参考,文中的示例代码介绍得很详细,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。
提前说明:从参数角度上看,其实都应该使用 char*,但是为了方便这里使用的都是 string。在 SO 上找到一个方式把 string 转成 char*,就是调用 string 的 c_str() 函数。
本文示例都是在 E:\database 路径下创建一个叫做 testFolder 的文件夹。
#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 我觉得 维基百科 上介绍的不错
#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 表示创建成功,-1 表示失败 //换成 ::_mkdir ::_access 也行,不知道什么意思 } return 0; }
#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 说明创建成功 } else { cout<<"Directory already exists."<<endl; } return 0; }
不推荐此方法,出错的话会有点麻烦。
#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; }
如果你出现了错误 undefined reference to imp__PathIsDirectory @ 4
,可以参考 undefined reference to imp PathIsDirectory
下面的方法是基于你详细阅读完上述链接后的前提下给出的
说我在 CodeBlocks 下解决该问题的方法:
第一步:在项目上右击,选择 Build Options
第二步: 在 Linker Settings 里添加 libshlwapi.a
文件
关于C++中实现创建文件夹的方法就介绍到这,上述方法和示例具有一定的借鉴价值,感兴趣的朋友可以参考,希望能对大家有帮助,想要了解更多大家可以关注群英网络其它的相关文章。
文本转载自PHP中文网
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。