ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

【C++】创建多级目录下的指定文件

2026/9/23 23:35:34 拓冰建站 浏览量
【C++】创建多级目录下的指定文件

文章目录

      • 一、判断文件存在
      • 二、获取文件所在目录
      • 三、创建指定目录
      • 四、使用方法

一、判断文件存在

static bool exists(const std::string &pathname)
{// 方法1 获取文件状态,若存在则可能获取成功,若不存在则一定失败struct stat st;if (stat(pathname.c_str(), &st) < 0){return false;}return true;//  方法2 access  是一个系统调用接口,使用后代码移植性不好//  return (access(pathname.c_str(), F_OK) == 0);
}

二、获取文件所在目录

static std::string path(const std::string &pathname)
{// ./abc/a.txtsize_t pos = pathname.find_last_of("/\\");if (pos == std::string::npos)return ".";return pathname.substr(0, pos + 1);
}

三、创建指定目录

static void createDirectory(const std::string &pathname)
{// ./abc/asize_t pos = 0, idx = 0;while (idx < pathname.size()){pos = pathname.find_first_of("/\\", idx);if (pos == std::string::npos){mkdir(pathname.c_str(), 0777);}std::string parent_dir = pathname.substr(0, pos + 1);if (!exists(parent_dir.c_str())){mkdir(parent_dir.c_str(), 0777);}idx = pos + 1;}
}

四、使用方法

// 输出格式 日志等级 时间 pid 内容
int main()
{// 判断文件所在目录是否存在if (!exists(path(log_file))) {// 创建目录createDirectory(path(log_file));}FILE* file = fopen(log_file.c_str(), "a+");if (file == nullptr) {std::cout << "open file failed" << std::endl;return;}fprintf(file, "%s\n", "hello world");
}