C++ 如何使用ofstream自动创建目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18682148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:08:03  来源:igfitidea点击:

How to create directories automatically using ofstream

c++filestream

提问by Kacper Fa?at

I am now writing an extractor for a basic virtual file system archive (without compression).

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

My extractor is running into problems when it writes a file to a directory that does not exist.

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

Extract function :

提取功能:

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;
}

ifsis the vfs root file, offsetis the value when the file starts, lengthis the file length and pathis a value from file what save offsets len etc.

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

For example path is data/char/actormotion.txt.

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

Thanks.

谢谢。

回答by Steve Jessop

ofstreamnever creates directories. In fact, C++ doesn't provide a standard way to create a directory.

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

Your could use dirnameand mkdiron Posix systems, or the Windows equivalents, or Boost.Filesystem. Basically, you should add some code just before the call to ofstream, to ensure that the directory exists by creating it if necessary.

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

回答by P0W

Its not possible with ofstreamto check for existence of a directory

无法ofstream检查目录是否存在

Can use boost::filesystem::existsinstead

可以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;
    }

回答by Ralphsoft IT Solutions

Creating a directory with ofstream is not possible. It is mainly used for files. There are two solutions below:

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

Solution 1:

解决方案1:

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

Solution 2:

解决方案2:

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