'windows cmd works via WinExec but not via popen

Why does the following code work via WinExec(), but not via popen()? It should do the same, right?

std::string command = "C:\\Windows\\system32\\cmd.exe /c \" cd /D \"C:\\Users\\Johannes\\Desktop\\test\" && xcopy /I .\\data\\*.* .\\build\\ \"";

WinExec(command.c_str(), SW_HIDE); //working

FILE *pipe = popen(command.c_str(), "r"); //NOT working

After some testing I'm even more confused, because some commands like mkdir work but not with xcopy:

1:

// not working
popen("C:\\Windows\\system32\\cmd.exe /c \" cd \"C:\\Users\\Johannes\\Desktop\\test\" && xcopy .\\data\\*.* .\\build\\ \"", "r");

2:

// working
popen("C:\\Windows\\system32\\cmd.exe /c \" cd \"C:\\Users\\Johannes\\Desktop\\test\" && mkdir test2 \"", "r");

3:

// not working 
popen("C:\\Windows\\system32\\cmd.exe /c \" cd \"C:\\Users\\Johannes\\Desktop\\test\" && xcopy \"C:\\Users\\Johannes\\Desktop\\test\\data\\*.*\" \"C:\\Users\\Johannes\\Desktop\\test\\build\\\" \"", "r");

4:

// working 
popen("C:\\Windows\\system32\\cmd.exe /c \" xcopy \"C:\\Users\\Johannes\\Desktop\\test\\data\\*.*\" \"C:\\Users\\Johannes\\Desktop\\test\\build\\\" \"", "r");


Solution 1:[1]

From the documentation (emphasis mine):

The _popen function creates a pipe. It then asynchronously executes a spawned copy of the command processor, and uses command as the command line.

So I think you should omit the cmd /c part and that should make it easier to get it to work.

Solution 2:[2]

I found a solution. If I do the following it works:

std::string command = "start cmd /c \" cd /D \"C:\\Users\\Johannes\\Desktop\\test\" && xcopy /I /E /C /Y .\\data\\*.* .\\build\\ \"";

or

std::string command = "cmd /c \" cd /D \"C:\\Users\\Johannes\\Desktop\\test\" && start xcopy /I /E /C /Y .\\data\\*.* .\\build\\ \"";.

From now on I will always do start cmd /c "", then it will always work in any case.

But one question remains. Why does it work like this and not otherwise?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paul Sanders
Solution 2 JohannesK71083