system() copy fails, while cmd copy works

两盒软妹~` 提交于 2019-12-24 08:38:41

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/237703/system-copy-fails-while-cmd-copy-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!