Home > Net >  How can i create a program in C that records terminal outputs into a text file?
How can i create a program in C that records terminal outputs into a text file?

Time:10-29

I work with a terminal and often i have to do it fast. Sometimes, rarely, i need to prove a point by looking at a terminal output from yesterday, for example.

I need my terminal entries to be saved in a text file and instead of copying and pasting the terminal output with my mouse, i want to practice C a bit (since apparently, i haven't done it much)

**Long story, short: I want my terminal output to be saved into a text file in the most automated way possible.**
Mad respect to anybody reading this.

CodePudding user response:

You might want to take a look at the screen utility (if you're using a supported operating system).

In order to log terminal output, you have to do something like what screen does, which is not possible to do in a portable fashion: create a monitor which sits between the terminal session and the terminal itself. In Unix-like systems, you can do that with a pseudoterminal. However, since a terminal is much more than a simple linear stream of characters -- it also supports arbitrary cursor movements, as well as recolouring and other style changes --, the log of the output also need to include console control codes. That makes it possible to replay the log, but it is not so easy to use it as a simple text file; additional work would have to be done in order to make that possible.

CodePudding user response:

Actually, interesting enough, i found a cool solution.

$script file.log 
$commands and whatnot 
$exit

and this saves a log file with all the outputs. It's pretty cool

I still want to do some C programming but I'm afraid that at this point it's really unnecessary.

Thank you, to everybody who participated in this topic. Mad love.

CodePudding user response:

A simple program that reads a command and prints to stdout using popen

#include <stdio.h>

int main(int argc, char **argv) {

    if (argc <= 1) {
        fprintf(stderr, "usage: %s cmd\n", argv[0]);
        return 1;
    }

    FILE *fp = popen(argv[1], "r");

    if (fp == NULL)
        return 1;

    char c;
    while ((c = fgetc(fp)) != EOF)
        fputc(c, stdout);
}
$ gcc main.c
$ ./a.out "ls"
a.out
main.c

If you want to save it to a different file, just change fputc(c, stdout) with your FILE*

  •  Tags:  
  • c
  • Related