1

So I'm doing a project for school and was trying to use the windows function "mkdir", but the directory name would be a string given by the program. Here's the (not very useful) code:

string c,a;
cin>>c;
if(c.compare("mkdir")==0)
    cin>>a;
    system("mkdir"); //here I want to make the directory
}
2
  • 4
    They're simpler ways to create directories... Commented Nov 30, 2017 at 14:02
  • On which operating system? I am surprised you are given this homework on Windows (however, coding a shell on Linux is a very common homework). Commented Nov 30, 2017 at 14:52

4 Answers 4

3

As others have mentioned, it would be better to create the directory without using the system call. If you would like to use that method regardless, you need to build a command string which includes your arguments prior to passing it to system.

char command[100];
sprintf(command, "mkdir %s", a);
system(command);
Sign up to request clarification or add additional context in comments.

1 Comment

I recommend using snprintf(command, sizeof(command), "mkdir %s", a);
2

Directories don't exist for the C++11 (or C++14) standard. Later C++ standard (e.g. C++17 ...) might offer the std::filesystem library.

You could use operating system specific primitives. On Linux and POSIX, consider the mkdir(2) system call (and CreateDirectory function on Windows).

You could find framework libraries (e.g. POCO, Qt, Boost, ....) wrapping these, so with these libraries you won't care about OS specific functions.

but the directory name would be a string given by the program.

Then you could consider building a command as a runtime C string for system(3). E.g. with snprintf(3) (or with some std::string operation). Beware of code injection (e.g. think of the malicious user providing /tmp/foo; rm -rf $HOME as his directory name on Linux)!

Comments

1

If you want create folder use WinApi see CreateFolder

Comments

0

The simplest solution I can think of:

string c;
cin >> c;
if(c == "mkdir") {
    string a;
    cin >> a;
    system("mkdir " + a);
}

But if this project involves writing some kind of command shell, system is very likely off-limits and you're expected to use the operating system's API directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.