ProAnswers.org

C Program to count number of lines in a file

1 Like

#include
int main()
/* Ask for a filename and count number of lines in the file*/
{

FILE *fp; //a pointer to a FILE structure
int no_lines = 0; //consider 40 character string to store filename
char filename[40], sample_chr;

printf(“Enter file name: “); //asks user for file name
scanf(”%s”, filename);
fp = fopen(filename, “r”); //open file in read mode
sample_chr = getc(fp); //get character from file and store in sample_chr

while (sample_chr != EOF)
{
//Count whenever sample_chr is ’
'(new line) is encountered
if (sample_chr == ’
')
{
//increment variable ‘no_lines’ by 1
no_lines=no_lines+1;
}
//take next character from file.
sample_chr = getc(fp);
}

fclose(fp); //close file.
printf("There are %d lines in %s
", no_lines, filename);
return 0;
}

Output:
Enter file name:abc.txt
There are 4 lines in abc.txt