2

Is there a way to read in the result of a command-line in a C program?

For example, if I have the following code in a C program

sprintf(command, "cat input_file.txt | wc -l");
system(command);

can I get the result of the wc -l and store it in a variable so I can use it in the same C program?

2 Answers 2

4

Yes, look into popen(), if you have it.

In general, you must spawn a sub-process and set up a pipe to read its standard output.

1

You can do

like

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int num_line;
   char *command="cat input_file.txt | wc -l";
   FILE *p=popen(command,"r");
   fscanf(p,"%d",&num_line);
   printf("%d\n",num_line);
   pclose(p);
   return 0;
}
1
  • Better use fscanf to avoid buffering.
    – kmkaplan
    Jul 9, 2014 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.