Aido
Aido

Reputation: 1584

ls command runnable in terminal not runnable in C++

I'm trying to run the command ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG} to get a list of wallpapers, and it runs fine in the terminal, but when I run it from C++ it tells me ls: cannot access /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}: No such file or directory. Does anyone know what's up?

The command I used to run it:

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;
}

Upvotes: 0

Views: 232

Answers (2)

Shnatsel
Shnatsel

Reputation: 4209

Wildcards like * are evaluated by the shell, so you'll have to invoke the shell directly to if you want it to process something for you.

For example, calling /bin/sh -c "ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG}" instead of ls /home/aidan/Pictures/Wallpapers/*/*.{jpg,JPG,png,PNG} will work. There is also a system call called system() that invokes a given command in the default shell for you.

However, using the shell to do the globbing is very dangerous if you pass untrusted user input to the shell. So try listing all the files and then using a native globbing solution to filter them instead of shell expansions.

Upvotes: 1

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17424

Wildcards like "*" or "{x,y,z}" are evaluated by the shell. If you run a program without intermediate shell, those are not evaluated but passed verbatim to the program, which should explain the error message.

Upvotes: 2

Related Questions