【问题标题】:How to create directories automatically using ofstream [duplicate]如何使用ofstream自动创建目录[重复]
【发布时间】:2013-09-11 23:49:23
【问题描述】:

我现在正在为基本的虚拟文件系统存档(不压缩)编写一个提取器。

我的提取器在将文件写入不存在的目录时遇到问题。

提取函数:

void extract(ifstream * ifs, unsigned int offset, unsigned int length, std::string path)
{
    char * file = new char[length];

    ifs->seekg(offset);
    ifs->read(file, length);

    ofstream ofs(path.c_str(), ios::out|ios::binary);

    ofs.write(file, length);
    ofs.close();

    cout << patch << ", " << length << endl;

    system("pause");

    delete [] file;
}

ifs 是 vfs 根文件,offset 是文件启动时的值,length 是文件长度,path 是文件中保存偏移量 len 等的值。

例如路径是 data/char/actormotion.txt。

谢谢。

【问题讨论】:

  • std::ofstream 是不可能的,它只用于写入文件。 boost 中可能有一个很好的包装器,可以在任意平台上创建目录。
  • @WhozCraig 这会很困难,因为这个档案在不同的目录中有 20 000 个文件。

标签: c++ filestream


【解决方案1】:

ofstream 从不创建目录。事实上,C++ 并没有提供创建目录的标准方法。

您可以在 Posix 系统或 Windows 等效系统或 Boost.Filesystem 上使用 dirnamemkdir。基本上,您应该在调用ofstream 之前添加一些代码,以确保在必要时通过创建目录来确保目录存在。

【讨论】:

  • +1 关于 C++ 没有创建文件系统目录的标准方法的注释常常让人们感到震惊。很高兴提及它。
  • 感谢您。我不知道..与我的代码斗争了几个小时,试图了解到底发生了什么。我可以写几天文件,但它突然停止了。没有意识到还有一段代码负责创建文件夹..
  • A standard way to create directories 已与 C++ 17 中的 std::filesystem 库一起添加。不过目前为 no compiler has supported it fully and officially
【解决方案2】:

ofstream 无法检查目录是否存在

可以改用boost::filesystem::exists

    #include <boost/filesystem.hpp>

    boost::filesystem::path dir("path");

    if(!(boost::filesystem::exists(dir))){
        std::cout<<"Doesn't Exists"<<std::endl;

        if (boost::filesystem::create_directory(dir))
            std::cout << "....Successfully Created !" << std::endl;
    }

【讨论】:

  • 这些方法现在是标准的一部分,目前在std::experimental::filesystem下可用
  • 不需要提升。
  • std::experimental::filesystem 是 C++17。对于 C++11 或更低版本仍需要使用 boost。
【解决方案3】:

无法使用 ofstream 创建目录。它主要用于文件。下面有两种解决方案:

解决方案 1:

#include <windows.h>
int _tmain() {
    //Make the directory
    system("mkdir sample");
}

解决方案 2:

#include <windows.h>
int _tmain() {
    CreateDirectory("MyDir", NULL);
}

【讨论】:

    猜你喜欢
    • 2012-09-13
    • 2022-12-08
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    相关资源
    最近更新 更多