C code to capture system data ()
How can I capture the output from the command system()
? For example, system("ls")
should get all files in this directory. I am using a Linux machine (if that matters). Also, I know what popen
can be used for data redirection as mentioned here.
Optimizing capturing stdout from system () command
but I specifically want to use the command system
. Is there a way to do this without redirecting the output to a file, for example system("ls >> filename")
?
Ok so I found a way to do this
dup2(out_pipe[1], STDOUT_FILENO);
close(out_pipe[1]);
system(command);
fflush(stdout);
read(out_pipe[0], buffer, MAX_LEN);
This can be used to redirect output from a system command using pipes
you can use popen () #include
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
popen(), pclose(): _POSIX_C_SOURCE >= 2 || _XOPEN_SOURCE || _POSIX_SOURCE _BSD_SOURCE || _SVID_SOURCE