0

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 :).

5
Contributors
6
Replies
8
Views
5 Years
Discussion Span
Last Post by OrangeTree
0

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.

0

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.

0

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.

1

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.

Edited by NicAx64

0

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.

0

Thanks for all replies :).

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

Edited by OrangeTree

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.