【问题标题】:ls command runnable in terminal not runnable in C++ls 命令在终端中可运行 在 C++ 中不可运行
【发布时间】:2015-07-09 16:35:31
【问题描述】:

我正在尝试运行命令 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;
}

【问题讨论】:

  • 显然 - 它不会扩展 {expression} 并将其视为文件名。
  • 也许您应该使用glob 函数而不是shell 命令?见stackoverflow.com/questions/8401777/…
  • /bin/sh 是否可以进行扩展?也许popen() 正在运行一个不为您执行{…} 扩展的shell。您可能需要运行 bash -c "ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}" 而不仅仅是 ls 命令。
  • @JonathanLeffler exec("/bin/sh -c \"ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}\"" 给出了同样的错误。
  • 我现在使用std::vector<std::string> walls = glob("/home/aidan/Pictures/Wallpapers/*/*.jpg") + glob("/home/aidan/Pictures/Wallpapers/*/*.JPG") + glob("/home/aidan/Pictures/Wallpapers/*/*.png") + glob("/home/aidan/Pictures/Wallpapers/*/*.PNG"); 和来自hereglob 和来自here+

标签: c++ linux ls


【解决方案1】:

像“*”或“{x,y,z}”这样的通配符由 shell 计算。如果您在没有中间 shell 的情况下运行程序,则这些程序不会被评估而是逐字传递给程序,这应该会解释错误消息。

【讨论】:

    【解决方案2】:

    像 * 这样的通配符由 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 进行 globbing 是 very dangerous。因此,请尝试列出所有文件,然后使用原生 globbing 解决方案来过滤它们,而不是使用 shell 扩展。

    【讨论】:

    • 我对 c++ 还很陌生,什么是 globbing?
    • Globbing 是文件名中“glob”(*) 的扩展,更一般地说,是文件名扩展。
    • 嗯。我将查看有关 glob 函数的评论。此外,exec("/bin/sh -c \"ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}\"" 给出了同样的错误。
    • 关于什么是 globbing 的问题,只需搜索网络,@AidanEdwards:duckduckgo.com/?q=globbing。关于错误,如果您在没有exec() 的情况下运行命令,即在 C++ 之外运行命令,输出是什么?
    猜你喜欢
    • 2021-02-17
    • 2017-04-08
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多