如何在C++中转义白色字符

How to escape white characters in C++

本文关键字:转义 白色 字符 C++      更新时间:2023-10-16

我试图使用 c++ 中的 system 关键字将文件复制到另一个文件夹,只要它不包含白色字符就可以正常工作

那么如何使"修复此问题"文件复制而没有错误呢?

#include <windows.h>
using namespace std;
void trial(){
//*"fix this" is the file's name that I want to copy*
system("copy fix this C:\users\public\");
system("pause");
}
C++与此

几乎没有关系。您的问题是如何将空格转义为输入到 Windows CMD 外壳的命令中;一般来说,这个问题是不平凡的,但在这种情况下,你可以简单地用双引号将文件名括起来,而双引号又必须像在C++字符串文本中一样进行转义:

system("copy "fix this" C:\users\public\");

话虽如此,调用 shell 来复制文件是没有意义的 - 您必须处理转义、错误报告、生成外部进程以获得已经可以从C++完成的事情。

鉴于您已经处于不可移植的区域(您的 cmd 命令.exe不能移植到其他 shell),您可以使用 CopyFile API:

if(!CopyFile("fix this", "c:\users\public\fix this", TRUE)) {
    std::cout<<"Couldn't copy filen";
}

此外,从 C++17 开始,终于有一种标准的、可移植的方法来复制文件。

使用双引号表示路径、copy "this is long path with spaces"system("copy "this is long path with spaces"");