C program to Find the Longest Line in a File

Problem:

Write a C program to find longest line in a file. Further also find the longest line from console input until user enters end of file key (Ctrl+D on Linux) while on terminal.

C program to find longest line in a file

#include<stdio.h>

#include<string.h>

int main()
{
	FILE *file;
	char line[200],fileName[50],max[200]=" ";

	printf("\n Enter the file name:- ");
	scanf(" %s",fileName);
 
	file=fopen(fileName,"r");

	if(file!=NULL)
	{
		while(fgets(line,sizeof(line),file)!=NULL) // read whole line
		{
			if(strlen(max)<strlen(line))
				strcpy(max,line);
		}

		printf("\n Longest line in file is:- ");
		printf("\n %s \n",max);

		fclose(file);
	}
	else
	{
	perror(fileName);
	}

	return 0;

}

Output of C program:


Now we are going to find the longest line from console input.

Algorithm to find longest line from console:

  1. Start
  2. Initialize counter variables to count lines,words and total characters.
  3. Accept characters until end of file character is not given using while loop.
  4. Increment counter to count total characters every time.
  5. If '\n' i.e. newline character is read, increment counter for lines.
  6. Do not include '\n' character in counting total characters.
  7. Display all the counts.
  8. Stop

C Program to find longest line from standard input:

#include<stdio.h>

int main()
{ 
	char ch;
	int line=0,word=0,count=0,maxchar=0,icount=0;
	printf("\n");

	while((ch=getchar())!=EOF)
	{
		++count;
		++icount;

		if(ch=='\n')
		{
		++line;
		--icount;
			if(icount>maxchar)
			{
			maxchar=icount;
			}
		icount=0;
		}
	} 
	printf("\n %d characters are written ",count);
	printf("\n \n %d characters are there in the longest line",maxchar);
	printf("\n \n %d lines are read \n \n",line);

	return 0;
}

/* Output of above code:-

Hi i am Abhijit

 16 characters are written 
 
 15 characters are there in the longest line
 
 1 lines are read
*/