- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a C program that displays contents of a given file like 'more' utility in Linux
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
#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\n"); return; } while ((ch = fgetc(fp)) != EOF){ putchar(ch); if (ch == '\n'){ 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
Advertisements