文件操作std::删除和std::重命名报告;没有这样的文件或目录;在带有空格的路径中,即使已转义 我想使用C++函数 STD::删除< /COD>和 STD::在我的代码(Linux操作系统)中重命名< /C> >,但是我在尝试这个代码的时候没有得到这样的文件或目录< /代码>错误。我怀疑这与路径中的空格有关

文件操作std::删除和std::重命名报告;没有这样的文件或目录;在带有空格的路径中,即使已转义 我想使用C++函数 STD::删除< /COD>和 STD::在我的代码(Linux操作系统)中重命名< /C> >,但是我在尝试这个代码的时候没有得到这样的文件或目录< /代码>错误。我怀疑这与路径中的空格有关,c++,string,C++,String,我的原始路径如下所示: std::string str = "path/to my/file"; std::remove(str.c_str()); std::string space_space(std::string instring) { std::string outstring; for (int i = 0; i < strlen(instring.c_str()); i++) { if (instring.c_str()[

我的原始路径如下所示:

std::string str = "path/to my/file";
std::remove(str.c_str());
std::string space_space(std::string instring) {
    std::string outstring;
    for (int i = 0; i < strlen(instring.c_str()); i++) {
        if (instring.c_str()[i] == ' ') {
            outstring += '\\';
            outstring += ' ';
        } else {
            outstring += instring.c_str()[i];
        }
    }
    return outstring;
}

std::string str = "path/to my/file"
std::remove(space_space(str).c_str());
当然,当我尝试将它与
ls
一起使用时,它会失败,因为它需要转义空间。我编写了一个函数来查找字符串中的空格并将其替换为转义空格。通过此函数时,上面的字符串变成
path/to\my/file
。所以我的工作看起来像:

std::string str = "path/to my/file";
std::remove(str.c_str());
std::string space_space(std::string instring) {
    std::string outstring;
    for (int i = 0; i < strlen(instring.c_str()); i++) {
        if (instring.c_str()[i] == ' ') {
            outstring += '\\';
            outstring += ' ';
        } else {
            outstring += instring.c_str()[i];
        }
    }
    return outstring;
}

std::string str = "path/to my/file"
std::remove(space_space(str).c_str());
std::string space\u space(std::string instring){
std::字符串扩展;
对于(int i=0;i

但是函数上的my
errno
仍然返回“没有这样的文件或目录”。为什么会发生这种情况?我如何修复它?

在您的
space\u space()
函数中,
strlen(instring.c\u str())
应该是
instring.size()
,而
instring.c\u str()[I]
应该是
instring[I]
。也就是说,您的函数是无用的,因为您实际上不需要从
\
开始转义空格。这不是真正的问题。如果你可以使用C++ 17或更高版本,考虑使用和替代.<代码>(int i=0;iStLLINN(INSTING,CXSTRE));I+++ <代码>——不仅应该是<代码> INSTING。siz()/Script >而不是<代码> StLLIN< /COD>,在循环的每次迭代中,你都调用<代码> StLLIN</代码>。你无缘无故地创建了一个
O(n^2)
循环。@RemyLebeau我正在使用C++17。@RemyLebeau@PaulMcKenzie谢谢你对for循环的批评,我会解决的。但与此同时,它为什么会起作用呢?测试返回
in:/path/to my/file out:/path/to\my/file