1.使用C++标准库创建(适用于141工具集)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <direct.h>
#include <iostream>
#include <filesystem>
#include <fstream>

int main() {
std::error_code ercode;

//获取当前路径
std::string curexe_path = _getcwd(NULL, 0);

//判断文件夹是否存在,不存在则创建
curexe_path = curexe_path + string("\\testlogcpp");
if (std::experimental::filesystem::exists(curexe_path, ecode) == false)
{
std::experimental::filesystem::create_directories(curexe_path, ecode);
}

//判断文件是否存在,不存在则创建
std::string file_path = curexe_path + "\\example.txt";
if (std::experimental::filesystem::exists(file_path)) {
std::cout << "File exists.\n";
} else {
std::cout << "File does not exist. Creating file...\n";
std::ofstream outfile(file_path);
outfile << "This is a new file.\n";
outfile.close();
std::cout << "File created.\n";
}
return 0;
}

注意:此种方法选择142工具集时会报错,因为在142中已经把filesystem::exists()从标准库中移除了。

2.使用windows标准库创建(适用于141和142工具集)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <fstream>
#include <direct.h>
#include <iostream>
#include <Windows.h>

//判断文件夹是否存在
bool isDirExist(const std::string& path) {
DWORD dwAttrib = GetFileAttributesA(path.c_str());
if (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) {
return true;
}
return false;
}

//创建文件夹
bool createDir(const std::string& path) {
if (CreateDirectoryA(path.c_str(), NULL)) {
return true;
}
return false;
}


int main()
{
//获取当前路径
std::string curexe_path = _getcwd(NULL, 0);
std::error_code ecode1;
std::string logpath = curexe_path + std::string("\\cpplog");

//若不存在则创建
if (!isDirExist(logpath))
createDir(logpath);

return 0;
}