【问题标题】:How to escape white characters in C++ [duplicate]如何在 C++ 中转义白色字符 [重复]
【发布时间】:2019-05-27 16:40:34
【问题描述】:

我试图使用 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++


【解决方案1】:

路径使用双引号,copy "this is long path with spaces"system("copy \"this is long path with spaces\"");

【讨论】:

    【解决方案2】:

    C++ 几乎与此无关。您的问题是如何将空格转义为输入 Windows CMD shell 的命令;一般来说,问题is nontrivial,但在这种情况下,您可以简单地用双引号将文件名括起来,而这又必须像在 C++ 字符串文字中一样被转义:

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

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

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

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

    另外,从 C++17 终于there's a standard, portable way to copy files

    【讨论】:

      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 2012-02-01
      • 2017-10-24
      • 2011-04-17
      相关资源
      最近更新 更多