C/C++检查文件夹是否存在并创建

本文介绍了一种在当前目录下创建日志文件夹的方法,并通过Windows API函数CreateDirectory检查文件夹是否存在,如果不存在则创建。
#include <Windows.h>

int main()
{
    char outputFolder[] = "./log/"; // create log file folder in current directory
    if (CreateDirectory(outputFolder, NULL) || // create folder if folder not exist
        ERROR_ALREADY_EXISTS == GetLastError())
    {
        // create files
    }
    else
    {
        // Failed to create directory.
    }

    return 0;
}
C++中,不同操作系统查看文件夹是否存在创建文件夹的代码实现有所不同。 ### Linux系统 在Linux系统中,可以使用`<unistd.h>`中的`access`函数来检查文件夹是否存在,使用`mkdir`函数来创建文件夹。示例代码如下: ```cpp #include <iostream> #include <string> #include <unistd.h> #include <sys/stat.h> int main() { std::string folderPath = "/<the_folder_path>"; if (access(folderPath.c_str(), F_OK) != 0) { std::cout << "Folder does not exist! Will create a new one!" << std::endl; if (mkdir(folderPath.c_str(), S_IRWXU) == 0) { std::cout << "Folder created successfully." << std::endl; } else { std::cerr << "Failed to create folder." << std::endl; } } else { std::cout << "Folder already exists." << std::endl; } return 0; } ``` ### Windows系统 在Windows系统中,可以使用`<direct.h>`中的`_access`函数来检查文件夹是否存在,使用`_mkdir`函数来创建文件夹。示例代码如下: ```cpp #include <iostream> #include <string> #include <direct.h> int main() { std::string folderPath = "C:\\<the_folder_path>"; if (_access(folderPath.c_str(), 0) != 0) { std::cout << "Folder does not exist! Will create a new one!" << std::endl; if (_mkdir(folderPath.c_str()) == 0) { std::cout << "Folder created successfully." << std::endl; } else { std::cerr << "Failed to create folder." << std::endl; } } else { std::cout << "Folder already exists." << std::endl; } return 0; } ``` ### 跨平台实现 若要实现跨平台代码,可以使用预处理指令根据不同的操作系统选择不同的函数。示例代码如下: ```cpp #include <iostream> #include <string> #ifdef _WIN32 #include <direct.h> #define access _access #define mkdir _mkdir #else #include <unistd.h> #include <sys/stat.h> #endif int main() { std::string folderPath = "/<the_folder_path>"; if (access(folderPath.c_str(), F_OK) != 0) { std::cout << "Folder does not exist! Will create a new one!" << std::endl; #ifdef _WIN32 if (mkdir(folderPath.c_str()) == 0) { #else if (mkdir(folderPath.c_str(), S_IRWXU) == 0) { #endif std::cout << "Folder created successfully." << std::endl; } else { std::cerr << "Failed to create folder." << std::endl; } } else { std::cout << "Folder already exists." << std::endl; } return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值