How to create directories automatically using ofstream

Kacper Fałat picture Kacper Fałat · Sep 8, 2013 · Viewed 49.9k times · Source

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.

Answer

Steve Jessop picture Steve Jessop · Sep 8, 2013

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.