Hi :).

I use this code to create a file:

#include <cstdlib>
#include <fstream>

using namespace std;

int main () {
    ofstream file("main/articles/giraffe/article.txt", ios::out);

    file.close ();
    return 0;
}

How can I simplify create path of folders (on unix system) "main/articles/giraffe/" - if folder "main" doesn't exist?
With using standard system libraries only.

Thanks :).

Recommended Answers

All 6 Replies

I don't think you can easily do it in a portable way using simple standard library calls. I would look at boost::filesystem if I were you.

If a non-portable way is enough for you, try the system() function from cstdlib, which works as though you have just typed the command given as a parameter in the command line.

If a non-portable way is enough for you, try the system() function from cstdlib

If you're using a *nix system, it would probably be cleaner to call the POSIX function int mkdir( const char *pathname, mode_t mode ) directly.

See here for the mkdir man-page.

Why ? Have your boss put a constrain on you that you should only use
standard library. However you could do it.

Remember the simple datastructure that you learned in your Datastructure class.
Which comes last in last out. Stack?

So use std::stack<std::string>.Push the 'main/articles/giraffe/' directory to the stack.
while (!  stack.is_empty() )
{
    cur_directory = stack.pop();
    if cur_directory exists then 
        // :FAIL THROUGH : 

    else
        get the parent_dir of the cur_directory 
        if parent_dir exists 
            create cur_dir 
         else
             push cur_directory;
             push parent_directory;
}

could you understand this psedo code and convert it to C++?
if not make a reply, I'll help you.

Take the pencil and paper and go through a dry run before you
push the compile button on your IDE.

Have your boss put a constrain on you that you should only use standard library. However you could do it.

Not with standard C++ since there's no concept of a directory, but using the system's standard API or a wrapper on top of it you certainly could. For a portable library I'll suggest Boost::FileSystem.

Thanks for all replies :).

NicAx64: It is school project. Stack is fine :), thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.