如何将文件保存到可能的新目录中?

发布于 2024-11-28 09:27:06 字数 529 浏览 4 评论 0原文

所以我有一些基本的 boost::filesystem::path Base 我想创建文件夹(如果不存在)并从字符串创建一个二进制文件。目前我有一个这样的功能:

void file_service::save_string_into_file( std::string contents, std::string name )
{
    std::ofstream datFile;
    name = "./basePath/extraPath/" + name;
    datFile.open(name.c_str(), std::ofstream::binary | std::ofstream::trunc | std::ofstream::out    );
    datFile.write(contents.c_str(), contents.length());
    datFile.close();
}

它需要目录才能存在。所以我想知道如何将我的函数更新为 boost.filesystem API 以达到所需的功能?

So I have some base boost::filesystem::path Base I want to create folder if one does not exist and create a binary file from string. Currently I have a function like this:

void file_service::save_string_into_file( std::string contents, std::string name )
{
    std::ofstream datFile;
    name = "./basePath/extraPath/" + name;
    datFile.open(name.c_str(), std::ofstream::binary | std::ofstream::trunc | std::ofstream::out    );
    datFile.write(contents.c_str(), contents.length());
    datFile.close();
}

It requires from the directories to exist. So I wonder how to update my function to boost.filesystem APIs in order to reach desired functionality?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美人骨 2024-12-05 09:27:06

请注意,为了使用 boost::filesystem 库,您需要链接预编译的 boost::filesystem 静态库和 boost::system 静态库。

#include "boost/filesystem.hpp"

boost::filesystem::path rootPath ( "./basePath/extraPath/" );
boost::system::error_code returnedError;

boost::filesystem::create_directories( rootPath, returnedError );

if ( returnedError )
   //did not successfully create directories
else
   //directories successfully created

Note that in order to use the boost::filesystem library, you will need to link against the pre-compiled boost::filesystem static library, and the boost::system static library.

#include "boost/filesystem.hpp"

boost::filesystem::path rootPath ( "./basePath/extraPath/" );
boost::system::error_code returnedError;

boost::filesystem::create_directories( rootPath, returnedError );

if ( returnedError )
   //did not successfully create directories
else
   //directories successfully created
极致的悲 2024-12-05 09:27:06

有一个 create_directories boost::filesystem 中的便利函数。它以递归方式创建目录,因此您不必自己遍历可能的新路径。

它位于 中。

There's a create_directories convenience function in boost::filesystem. It creates directories recursively, so you don't have to traverse the possibly new path yourself.

It's in <boost/filesystem/convenience.hpp>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文