P
P
parkito2016-05-27 00:13:40
linux
parkito, 2016-05-27 00:13:40

How to store the result of a system command call?

Hello. Please help me understand the following question:
In a C / C ++ program, using a command in bash, I need to count the number of lines in a file containing the letter a . I am writing a program.

#include<stdio.h>
int main() {
      
    system("cat 1.txt | grep -c \"a\" ");
       return 0;
}

But I need to capture the output of system("cat 1.txt | grep -c \"a\" "); to a variable within the program itself. Something like this int i = system("cat 1.txt | grep -c \"a\" "); . How can this be organized?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2016-05-27
@jcmvbkbc

man popen

#include <stdio.h>

int main()
{
    int n;
    FILE *f = popen("grep -c \"a\" < 1.txt", "r");
    fscanf(f, "%d", &n);
    pclose(f);
    ...
}

#
#algooptimize #bottize, 2016-05-27
@user004

perversion, but,
redefine console out with a string stream, run a command, change out back, output a line.
Run a process that will have an out in your pipe, etc.

A
abcd0x00, 2016-05-27
@abcd0x00

The most optimal would be to add output redirection to a file to the command passed to system (), and then read this file through fopen (). After all, remove the file with remove().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question