Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 08 May, 2017

Write a C program that displays contents of given line page by page. Given number of lines to show as ‘n’ at a time and a file name, the program should first show n lines, then wait for user to hit a key before showing next n lines and so on.

We strongly recommend to minimize the browser and try this yourself first.

We can open the given file and print contents of files. While printing, we can keep track of number of newline characters. If the number of newline characters become n, we wait for the user to press a key before showing next n lines.

Following is the requires C program.

// C program to show contents of a file with breaks
#include <stdio.h>
// This function displays a given file with breaks of
// given line numbers.
void show(char *fname, int n)
    // Open given file
    FILE *fp = fopen(fname, "r");
    int curr_lines = 0, ch;
    // If not able to open file
    if (fp == NULL)
        printf("File doesn't exist\n");
    // Read contents of file
    while ((ch = fgetc(fp)) != EOF)
        // print current character
        // If current character is a new line character,
        // then increment count of current lines
        if (ch == '\n')
            // If count of current lines reaches limit, then
            // wait for user to enter a key
            if (curr_lines == n)
                curr_lines = 0;
// Driver program to test above function
int main()
    char fname[] = "A.CPP";
    int n = 25;
    show(fname, n);
    return 0;

This article is contributed by Ajay Jain. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!