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