- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
C Program to count the number of lines in a file?
In this program, we are going to learn how to find the total number of lines available in a text file using C program?
This program will open a file and read the file’s content character by character and finally return the total number of lines in the file. To count the number of lines we will check the available Newline (
) characters.
Input: File "test.text" Hello friends, how are you? This is a sample file to get line numbers from the file. Output: Total number of lines are: 2
Explanation
This program will open a file and read the file’s content character by character and finally return the total number of lines in the file. To count the number of lines we will check the available Newline (
) characters. This will check all the new line and count then and return the count.
Example
#include<iostream> using namespace std; #define FILENAME "test.txt" int main() { FILE *fp; char ch; int linesCount=0; //open file in read more fp=fopen(FILENAME,"r"); if(fp==NULL) { printf("File \"%s\" does not exist!!!
",FILENAME); return -1; } //read character by character and check for new line while((ch=fgetc(fp))!=EOF) { if(ch=='
') linesCount++; } //close the file fclose(fp); //print number of lines printf("Total number of lines are: %d
",linesCount); return 0; }
- Related Articles
- C# Program to count the number of lines in a file
- C program to count characters, lines and number of words in a file
- How to count the number of lines in a text file using Java?
- How to count the total number of lines in the file in PowerShell?
- Write a C program to find total number of lines in an existing file
- C# Program to read all the lines of a file at once
- C# Program to read all the lines one by one in a file
- C# program to count the number of words in a string
- Python Program to Read First n Lines of a File
- C/C++ Program to Count trailing zeroes in factorial of a number?
- Golang Program to Count the Number of Digits in a Number
- C# program to count total bits in a number
- Counting number of lines in text file using java
- How to count the number of words in a text file using Java?
- Program to count number of unique subsequences of a string in C++

Advertisements