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

Asked

Viewed 83 times

1

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

I need to collect this information that is printed on the screen but instead of being printed on the screen be routed to a vector and later 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 body of the code?

  • The man fprintf basic has many control characters in output. You can filter these characters with the program col: man fprintf | col -b

2 answers

2

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

1


Tell you what, I didn’t test it, but the solution that popped into my head was.

We assume the command:

man fprintf > saida.txt

Saves terminal output in a text file somewhere on the pc.

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

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

The next step is to just use c functions that read that file. Then you treat it the way you think best.

  • 1

    Valgrind is used to detect memory Leaks. What outputs the printout to the file is >

  • Thanks for the @krystalgamer fix.

  • system("man fprintf > output.txt"); was exactly what I needed, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.