system() copy fails, while cmd copy works
Question
In cmd.exe, I can execute the command "copy c:\hello.txt c:\hello2.txt" and it worked fine. But in my C program, I ran this piece of code and got the following error:
#include <iostream>
using namespace std;
int main()
{
system("copy c:\hello.txt c:\hello2.txt");
system("pause");
return 0;
}
Output: The system cannot find the file specified.
Anybody know what is going on here?
Solution
Inside C strings (and quite a few other languages that use the same escaping rules), \
should be \\
since it's the escape character. It allows you to enter, in normal text, non-printable characters such as:
- the tab character
\t
. - the carriage-return character
\r
. - the newline character
\n
. - others which I won't cover in detail.
Since \
is used as the escape character, we need a way to put an actual '\'
into a string. This is done with the sequence \\
.
Your line should therefore be:
system("copy c:\\hello.txt c:\\hello2.txt");
This can sometimes lead to obscure errors with commands like:
FILE *fh = fopen ("c:\text.dat", "w");
where the \t
is actually the tab
character and the file that you're trying to open is:
c:TABext.dat.
OTHER TIPS
Alternatively, all the Windows functions support Unix style slashes
system("copy c:/hello.txt c:/hello2.txt");
Some people prefer this since it's easier to spot an odd '\'.
But it might confuse Windows users if you display this path in a message.