如何使用ofstream自动创建目录

Kac*_*łat 26 c++ filestream

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

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

提取功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

例如,path是data/char/actormotion.txt.

谢谢.

Ste*_*sop 29

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

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

  • 关于C++没有标准方法制作文件系统目录的注释经常给人们带来震撼.很高兴提到它. (7认同)
  • [创建目录的标准方法](http://en.cppreference.com/w/cpp/filesystem/create_directory)已与C++ 17中的`std :: filesystem`库一起添加.目前[没有编译器支持它完全正式](http://en.cppreference.com/w/cpp/compiler_support#C.2B.2B17_features). (4认同)

P0W*_*P0W 18

ofstream检查目录是否存在是不可能的

可以boost::filesystem::exists改用

    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::end;
    }
Run Code Online (Sandbox Code Playgroud)

  • `std::experimental::filesystem` 是 C++17。对于 C++11 或更低版本仍然需要使用 boost。 (4认同)
  • 这些方法现在是标准的一部分,目前可在`std :: experimental :: filesystem`下使用 (3认同)

小智 7

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

解决方案1:

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

解决方案2:

#include <windows.h>
int _tmain() {
    CreateDirectory("MyDir", NULL);
}
Run Code Online (Sandbox Code Playgroud)