Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create directories automatically using ofstream [duplicate]

Tags:

c++

filestream

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.

like image 654
Kacper Fałat Avatar asked Sep 08 '13 09:09

Kacper Fałat


People also ask

Does ofstream create directory?

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.

How do I create a directory and file in C++?

Problem: Write a C/C++ program to create a folder in a specific directory path. This task can be accomplished by using the mkdir() function. Directories are created with this function.

How do I create a directory in CPP?

For this open a command prompt, navigate to the folder where you want to create a new folder using cd. Then use command mkdir followed by the name of the folder you want to create. After that you can simply use command dir to check if the folder has been created.

Does ofstream create a file?

To create a file, use either the ofstream or fstream class, and specify the name of the file. To write to the file, use the insertion operator ( << ).


2 Answers

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.

like image 163
Steve Jessop Avatar answered Oct 24 '22 02:10

Steve Jessop


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

Can use boost::filesystem::exists instead

    #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;
    }
like image 19
P0W Avatar answered Oct 24 '22 00:10

P0W