Write the c program to create a file "input.txt". Open the file and read the content to count the number of lines.
Rule to implement the above problem:
The file name should be input.txt.
Input format:
Give the input as a file.
Output format:
The output will be the integer which is the number of lines in the file. Display the output in the console.
Sample Input file (input.txt):
C was invented to write an operating system.
C is a successor of B language.
C is a Structured language.
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computers.
Implementation of the above problem
#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
// Open the file
fp = fopen("input.txt", "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 has %d lines",count);
return 0;
}
Output:
The file has 6 lines
Thanks
Mukesh Rajput
Post A Comment:
0 comments: