【问题标题】:How to use std::fstream, boost, or anything else to create a folder file如何使用 std::fstream、boost 或其他任何东西来创建文件夹文件
【发布时间】:2011-10-11 22:06:51
【问题描述】:

嘿,我刚刚了解了 STL i/o,它引导我进行 boost::Serialize 和 Archive,所以我几乎知道如何制作任何类型的文件,除了 文件夹保存/收集我形成的文件。

如何使用代码创建文件夹?最好使用 boost::Serialize 或 STL?
如果它也是独立于平台的,那就太好了!


好的,现在我已经查看/尝试使用 boost::filesystem。但是,当我查看参考文档时,关于 create_directory(); 的信息并不多。 我留下了这样的问题:如果目录已经存在怎么办?

bool create_directory(const path&p); bool create_directory(const 路径& p, system::error_code& ec);效果:尝试创建 目录 p 解析为,好像通过 POSIX mkdir() 与第二个参数 S_IRWXU|S_IRWXG|S_IRWXO。

后置条件:is_directory(p)

返回:如果创建了新目录则返回 true,否则返回 false。

抛出:如错误报告中所述。

我正在尝试运行以下代码,并检查是否已创建新文件夹,或者我现在理解为目录 =)。我一个也找不到!为什么?它返回 true =/

  path testPath("C:\\Users\\Howlett\\Documents\\Visual Studio 2010\\Projects\\boost tests\\newFolderTest");
  bool success = create_directory(testPath);
  bool success2= create_directory("C:\\Users\\Howlett\\Documents\\Visual Studio 2010\\Projects\\boost tests\\Test\\NestedFolderTest");

【问题讨论】:

  • 你没有提到函数返回true还是false。
  • @Nicol Bolas 它确实返回 true。

标签: file serialization boost stl directory


【解决方案1】:

也许您应该寻找一个文件系统 库,它可能提高您在此任务中的工作效率。它甚至可能被称为Boost.Filesystem ;)

这是一个非常好的处理文件系统内容的库。 boost::filesystem::create_directory 将涵盖您的具体任务。


以下源代码有效。如果它没有创建目录,那么您应该刷新 Windows 资源管理器以确保它确实在查找。如果你运行程序两次,第二次会打印错误信息。

#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main(int argc, const char *argv[])
{
    fs::path thePath = fs::current_path();
    std::cout << thePath << std::endl;

    fs::path newDir = thePath / "newDir";
    std::cout << newDir << std::endl;

    bool bDidCreate = fs::create_directory(newDir);

    if(!bDidCreate)
        std::cout << "Directory creation failed!" << std::endl;

    return 0;
}

【讨论】:

  • 感谢您的链接,但我还是有点困惑!你能看看我对这个问题的编辑吗?
猜你喜欢
  • 2010-12-08
  • 1970-01-01
  • 2010-12-15
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多