c++ - 不断删除字符串会导致无限循环

标签 c++ linux stdstring

我想做的是获取一条路径,然后逐个目录不断地删除路径,随时检查它是否是符号链接(symbolic link)。这是我所拥有的:

static bool isLinkDirInSymLink (std::string linkPath)
    {
    DIR *baseDir;
    struct dirent *currentDir;

    do
        {
        baseDir = opendir(linkPath.c_str());
        if (baseDir)
            {
            currentDir = readdir(baseDir);
            if (currentDir->d_type == DT_LNK)
                return true;
            }
        linkPath.erase (linkPath.find_last_of("/") + 1, linkPath.find_first_of("\0"));
        } while (strcmp(linkPath.c_str(), "") != 0);

    return false;
    }

这陷入了无限循环。当我在 gdb 中运行程序时会发生什么是我发送一个 linkPath/home/user/test/linktest/out/mDirs/testDir1/test , 当这成功删除并且我剩下的是 /home/user/test/linktest/out/mDirs/testDir1 ,然而这是无限循环开始的地方。即使这与进入 erase 时的第一条路径格式相同, 什么都没发生。我尝试了很多不同的 erase 变体。来自 here但似乎都不起作用。我也试过linkPath.append('\0')因为我认为最后可能是空字符的问题。

谢谢大家,这就是我最终得到的:

char realPath[MAX_FILELENGTH];

do
    {
    if (realpath (linkPath.c_str(), realPath) != NULL)
        if (strcmp(linkPath.c_str(), realPath) != 0)
            return true;

    size_t eraseFrom = linkPath.rfind('/');
    if (std::string::npos != eraseFrom)
        linkPath.erase(eraseFrom);
    } while ( !linkPath.empty() );

return false;

最佳答案

由于 + 1 在你的 erase 调用中,你正在删除从 / 到字符串末尾之前的字符,删除以下字符:

/home/user/test/linktest/out/mDirs/testDir1/test\0
                                            ^^^^

循环的第一次迭代将删除 test,留下 /home/user/test/linktest/out/mDirs/testDir1/。所有对 erase 的后续调用都不会执行任何操作,因为 /\0 之间的字符为零。

您应该在删除调用中从 linkPath.find_last_of("/") + 1 中删除 + 1,这样结尾的斜线也会被删除。

此外,erase(size_t, size_t) 重载实际上将要删除的部分的长度 作为第二个参数 - find_first_of 返回找到的字符的索引,而不是它的迭代器。您的代码仅在偶然情况下起作用。使用 std::string::npos,它将删除所有内容直到结束,而不是 \0 字符的位置(如果你还没有调用 c_str()

关于c++ - 不断删除字符串会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31590945/

相关文章:

c++ - 什么是 SDL 渲染器?

linux - Bash 脚本手动执行正常运行但不使用 crontab

linux - 将时间戳添加到 shell 脚本的 cat 输出

c++ - 如何将各种类型的 vector 转换为 std::string?

c++ - 将 STL 字符串数组转换为 const char* 数组的最有效方法是什么?

c++ - OpenGL绘制倒三角形

c++ - 为什么STL的Map中的值没有变化?

linux - 读取 USB UPS 状态的 Bash 脚本

c++ - 如何将string中的每个字符都改成 'n'在前面?

c++ - 图像中的 Opencv 评级特征