Search code examples
c++stringdirectorystringstream

Is there better way to create directory from string? cpp, create directory, stringstream, string.


My code is working but I think it is awful way to do it. (Using system() has a security issues, and also creating string just because ss.str() is not accepted). Do you know any better way?

    stringstream ss;
    string dir;

    // make dir output
    ss.str(""); // set  empty
    ss.clear(); // clear bit flags
    ss << "mkdir \"" << argv[2] << "\"";
    dir = ss.str();
    system(dir.c_str());

argv[2] is from: int main (int argc, char *argv[]) {...

Any better ideas?


Solution

  • You should either use the portable Boost.Filesystem Library which provides the function create_directory or use the facilities your target environment provides, e.g. the POSIX function mkdir for Linux.

    Boost also provides functionality to create a path, just look around in the reference to find what you need.

    Using the system command is a bad idea.


    If you and your professor are using MSVC 2015 or gcc5.3 or newer, you can probably use the experimental implementation of C++1z's create_directory. It is based on Boost, but Boost is much wider supported.