Write a C program that displays contents of a given file like 'more' utility in Linux

C++Server Side ProgrammingProgramming

Here, we will write a C program that will display the contents of a file page by page as displayed in Linux using the more command.

This program will show a specific number of lines on the screen first and then wait for the user to hit enter to move to the next page i.e. next set of n lines.

For displaying the content of the file like this we will open the file and print its contents. And maintain a counter for new lines in the file. When this counter reaches n, we will read a key pressed by the user to print further new n lines.

Example

 Live Demo

#include <stdio.h>
void displaytext(char *fname, int n) {
   FILE *fp = fopen(fname, "r");
   int lineCount = 0, ch;
   if (fp == NULL) {
      printf("No such file exists
");       return;    }    while ((ch = fgetc(fp)) != EOF){       putchar(ch);       if (ch == '
'){          lineCount++;          if (lineCount == n){             lineCount = 0;             getchar();          }       }    }    fclose(fp); } int main() {    char fname[] = "main.CPP";    int n = 10;    displaytext(fname, n);    return 0; }

Output

No such file exists
raja
Updated on 17-Jul-2020 10:48:40

Advertisements