文章目录
- 一、判断文件存在
- 二、获取文件所在目录
- 三、创建指定目录
- 四、使用方法
一、判断文件存在
static bool exists(const std::string &pathname)
{struct stat st;if (stat(pathname.c_str(), &st) < 0){return false;}return true;
}
二、获取文件所在目录
static std::string path(const std::string &pathname)
{size_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)
{size_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;}
}
四、使用方法
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");
}