Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect the output of a system call to inside the program in C/C++?

I'm writing a program in C++ which do some special treatment for all the files in the current directory on Linux OS.

So i was thinking of using system calls such as system("ls") to get the list of all files.

but how to store it then inside my program ? ( how to redirect the output of ls to let's say a string that i declared in the program )

Thanks

like image 668
Debugger Avatar asked Apr 16 '10 18:04

Debugger


People also ask

What is output redirection in C?

Before the C shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output. You can redirect the standard input and output of a command with the following syntax statements: Item.

What is the proper way to redirect the output of the Is command to a file named?

Regular output append >> operator The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file.


2 Answers

The consensus seems to be not to use "ls". However, for anyone that is interested in a function to do this:

/**
 * Execute a command and get the result.
 *
 * @param   cmd - The system command to run.
 * @return  The string command line output of the command.
 */
string GetStdoutFromCommand(string cmd) {

    string data;
    FILE * stream;
    const int max_buffer = 256;
    char buffer[max_buffer];
    cmd.append(" 2>&1"); // Do we want STDERR?

    stream = popen(cmd.c_str(), "r");
    if (stream) {
        while (!feof(stream))
            if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
        pclose(stream);
    }
    return data;
}
like image 127
SuperJames Avatar answered Nov 15 '22 08:11

SuperJames


I don't think you can use system to read the output.

Try using popen.

   #include <stdio.h>

   FILE *popen(const char *command, const char *type);

   int pclose(FILE *stream);

But, you probably don't want to do this for ls. Two reasons:

  • If you want to get a directory listing use the file system api directly (readdir), instead of using shell commands and parsing it.
  • Someone pointed me to a blog post recently explaining why parsing ls output is a bad idea.
like image 42
Stephen Avatar answered Nov 15 '22 09:11

Stephen