How to use a CMD command in c++?

2019-09-22 06:36发布

I want to use this cmd command

ROBOCOPY D:\folder1 D:\folder2 /S /E

with conditions to copy the contents of folder1 to folder2

if(i == 1)

and,

if(i == 2)

ROBOCOPY D:\folder3 D:\folder4 /S /E

to copy the contents of folder3 to folder4

what should i do?

标签: c++ cmd
2条回答
看我几分像从前
2楼-- · 2019-09-22 06:45

The simplest way is to call the standard library function system: http://www.cplusplus.com/reference/cstdlib/system/

If you need more flexibility, http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx CreateProcess is the thing to go for - the STARTUPINFO argument lets you do things like pass it custom input and capture its output too.

查看更多
3楼-- · 2019-09-22 06:51

"what should i do?"

You simply do this (using the std::system() function):

#include <cstdlib>

// ...

if(i == 1) {
    std::system("ROBOCOPY D:/folder1 D:/folder2 /S /E");
}
else if(i == 2) {
    std::system("ROBOCOPY D:/folder3 D:/folder4 /S /E");
}

Note that for string literals like "D:\folder3", you'll need to escape '\' characters, with another '\': "D:\\folder3".
Or even two more, depending on the interpreting command shell (should work on windows without doing so): "D:\\\\folder3".
The easier way though, is to use the simpler to write '/' character, that's accepted for specifying windows pathes lately as well.

查看更多
登录 后发表回答