1 c command copy escaping system
在cmd.exe中,我可以执行命令"copy c:\ hello.txt c:\ hello2.txt",它运行正常.但在我的C程序中,我运行了这段代码并得到以下错误:
#include <iostream>
using namespace std;
int main()
{
system("copy c:\hello.txt c:\hello2.txt");
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:系统找不到指定的文件.
谁知道这里发生了什么?
pax*_*blo 17
内部C字符串(以及使用相同转义规则的其他一些语言)\应该是\\因为它是转义字符.它允许您以普通文本输入不可打印的字符,例如:
\t.\r.\n.由于\用作转义字符,我们需要一种将实际 '\'放入字符串的方法.这是通过序列完成的\\.
因此,您的行应该是:
system("copy c:\\hello.txt c:\\hello2.txt");
Run Code Online (Sandbox Code Playgroud)
这有时会导致模糊错误,例如:
FILE *fh = fopen ("c:\text.dat", "w");
Run Code Online (Sandbox Code Playgroud)
其中,\t实际上是tab性格和你试图打开该文件是:
c:TABext.dat.