Search code examples
clinuxmanpage

Clearing a terminal similar to man page using C


I want to read a text file and display it. But I need to print it on terminal, similar to the man page (linux). That is, when scrolled up, it shouldn't go beyond the first line and scrolling down shouldn't go beyond the last line. I have to program it only in C. I shouldn't use any tools. My current coding for clearing a terminal alone is,

#include<stdio.h>

main()
{
printf("\033[2J");
printf("\033[0;0f");
FILE *ffp;
char c;

ffp=fopen("help.txt","r");
while((c=getc(ffp))!=EOF)
    printf("%c",c);
}

Kindly guide me. Thanks in advance.

UPDATED:

main()
{
FILE *ffp;
char c;


ffp=fopen("help.txt","r");

FILE *less = popen("less", "w");
while ((c = getc(ffp)) != EOF) {
  fputc(c, less);
}
}

Solution

  • FILE *less = popen("less", "w");
    while ((c = getc(ffp)) != EOF) {
      fputc(c, less);
    }
    

    more and less are the programs that implement scrolling through a file or pipe a screenful at a time.