3

How can I capture the output from system() command? For example system("ls") should get me all the files in that directory. I am using a linux machine (if that makes any difference). Also I know popen can be used to redirect the data as has been answered here

Capturing stdout from a system() command optimally

but I specifically want to use the system command. Is there any way to do it without redirecting the output to a file like system("ls >> filename")?

Community
  • 1
  • 1
  • The answers in that question show how to do it: use `popen()` instead of `system()`. What's the problem? – Barmar Jul 26 '15 at 05:26
  • As I said I don't wanna use popen I want to use system() – Saransh Singh Jul 26 '15 at 05:26
  • 1
    If you use `system()`, you have to redirect to a file and then read the file. – Barmar Jul 26 '15 at 05:27
  • 3
    Why don't you want to use `popen()` when it's exactly the right function for this? – Barmar Jul 26 '15 at 05:28
  • 3
    The definition of the question which I'm trying to solve specifically says use system() – Saransh Singh Jul 26 '15 at 05:31
  • 1
    Well, `system()` doesn't provide any way to capture the output by itself. That's the whole difference between `system` and `popen`. – Barmar Jul 26 '15 at 05:36
  • 1
    I think that you cant do that thing because system() returns the value of the code execution, and execute a fork to throw the command. if you still want to work with system you'll need to redirect. – Horacio Jul 26 '15 at 05:36
  • 2
    The sequence of calls starts with `pipe` and `fork`, followed by `dup2`, `close`, `close`, `system` in the child, and `close`, `read`, `close` in the parent. – user3386109 Jul 26 '15 at 05:59

2 Answers2

0

Ok so I found a way to do so

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 the output from a system command using pipes

-2

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
Liyuan Liu
  • 172
  • 2