/* C Program to count the Number of Lines in a Text File */#include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be // either in current folder or complete path should be provided printf("Enter file name: "); scanf("%s", filename); // Open the file fp = fopen(filename, "r"); // Check if file exists if (fp == NULL) { printf("Could not open file %s", filename); return 0; } // Extract characters from file and store in character c for (c = getc(fp); c != EOF; c = getc(fp)) if (c == '\n') // Increment count if this character is newline count = count + 1; // Close the file fclose(fp); printf("The file %s has %d lines\n ", filename, count); return 0; } |
chevron_right
filter_none
Output:
Enter file name: countLines.c The file countLines.c has 41 lines
Please write comments if you find anything incorrect or want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Lex program to take input from file and remove multiple spaces, lines and tabs
- Lex program to count the number of lines, spaces and tabs
- Implement your own tail (Read last n lines of a huge file)
- C program to copy contents of one file to another file
- Program to print last 10 lines
- C Program to count the Number of Characters in a File
- How to use getline() in C++ when there are blank lines in input?
- Print 2D matrix in different lines and without curly braces in C/C++?
- How to write long strings in Multi-lines C/C++?
- Program to delete a line given the line number from a file
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program to print contents of file
- C Program to merge contents of two files into a third file
- C program to delete a file
- C++ program to print unique words in a file
- C Program for Lower Case to Uppercase and vice-versa in a file
- C++ program to read file word by word
- C++ program to append content of one text file to another
- LEX program to add line numbers to a given file
- C Program to find size of a File

