ls 命令在终端中可运行,在 C++ 中不可运行

ls command runnable in terminal not runnable in C++

我正在尝试 运行 命令 ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG} 获取壁纸列表,它 运行 在终端中没问题,但是当我 运行它来自 C++,它告诉我 ls: cannot access /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}: No such file or directory。有人知道怎么回事吗?

我用来运行的命令是:

std::string exec(std::string command) {
    const char *cmd = command.c_str();
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
    return result;
}

“*”或“{x,y,z}”等通配符由 shell 计算。如果你 运行 一个没有中间体的程序 shell,那些不会被评估而是逐字传递给程序,这应该解释错误消息。

像 * 这样的通配符由 shell 求值,所以如果您想让它为您处理某些事情,您必须直接调用 shell。

例如,调用 /bin/sh -c "ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}" 而不是 ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG} 将起作用。还有一个名为 system() 的系统调用,它会为您调用默认 shell 中的给定命令。

但是,如果您将不受信任的用户输入传递给 shell,则使用 shell 进行通配是 very dangerous。因此,请尝试列出所有文件,然后使用本机 globbing 解决方案来过滤它们而不是 shell 扩展。