How to create directories automatically using ofstream [duplicate]

女生的网名这么多〃 提交于 2019-12-03 10:45:34

问题


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

ifs is the vfs root file, offset is the value when the file starts, length is the file length and path is a value from file what save offsets len etc.

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

Thanks.


回答1:


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

Your could use dirname and mkdir on 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.




回答2:


Its not possible with ofstream to check for existence of a directory

Can use boost::filesystem::exists instead

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



回答3:


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

Solution 1:

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

Solution 2:

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


来源:https://stackoverflow.com/questions/18682148/how-to-create-directories-automatically-using-ofstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!