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
}
Jt Maston
  • 25
  • 8
  • 4
    They're [simpler ways](https://msdn.microsoft.com/fr-fr/library/windows/desktop/aa363855(v=vs.85).aspx) to create directories... – YSC Nov 30 '17 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). – Basile Starynkevitch Nov 30 '17 at 14:52

4 Answers4

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);
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)!

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

If you want create folder use WinApi see CreateFolder

Ashwel
  • 1,194
  • 9
  • 16
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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82