how to capture what is printed on the console by means of a command into a vector in C language

1

When I do some command in the linux console, for example man fprintf , a series of information is printed on the screen.

I need to collect this information that is printed on the screen but instead of being printed on the screen it is forwarded to a vector and subsequently to a file.

What is the way I have to capture what is written on the screen and forward it to a vector that exists in the code body?

    
asked by anonymous 21.12.2015 / 23:32

2 answers

1

Do the following, did not test, but the solution that came to mind was.

We assume that the command:

man fprintf > saida.txt

Save terminal output to a text file somewhere on the pc.

But how to run this command within your program? For this there is a function called system . Logo

system("man fprintf > saida.txt");

The next step is to only use c functions that read this file. There you treat it any way you like.

    
22.12.2015 / 01:15
2

On POSIX systems you can do what you want with popen() .

Possibly there are other specific ways for specific operating systems (Windows, Android, iOS, MINIX, NeXTSTEP, ...)

Example

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

int main(void) {
    char info[1000000]; // 1 Mbytes deve chegar :-)
    size_t infolen = 0;
    char linha[1000];
    size_t linhalen;
    char comando[] = "man fprintf";
    FILE *processo;

    processo = popen(comando, "r");
    if (!processo) {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    while (fgets(linha, sizeof linha, processo)) {
        linhalen = strlen(linha);
        if (infolen + linhalen >= sizeof info) {
            fprintf(stderr, "O output tem muitas linhas.\n");
            exit(EXIT_FAILURE);
        }
        strcpy(info + infolen, linha);
        infolen += linhalen;
    }
    pclose(processo);

    // usa info, por exemplo imprime os 6 primeiros caracteres
    printf("%.6s", info);

    return 0;
}
    
22.12.2015 / 10:28