Rayne
Rayne

Reputation: 14977

Get result of command-line in C program

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?

Upvotes: 2

Views: 549

Answers (2)

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25865

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

Upvotes: 1

unwind
unwind

Reputation: 399713

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.

Upvotes: 4

Related Questions