C File Handling Programs 14

Reading File: Line by Line

Question:26
Write a C program to read a file line by line, Further, display it on the screen
//to read the contents of the file line by line
Sol:

#include<stdio.h>
#include<conio.h>
int main()
{
   FILE *fp;
   char buff[255];
   fp = fopen("test11.txt", "r");
   if(fp==NULL)
   {
   	printf("Unable to open the file\n");
   	return(0);
   }
   while(1)
   {

     fgets(buff, 255,fp); //reads  line by line
    if(feof(fp))
   {
     printf("\n\n\nend of file");
     break;
   }
     printf("%s\n", buff );
   }
   fclose(fp);
   getch();
   return(0);
}

Question:27
Write a C program to read a file line by line, display it on the screen along with the length of each line.
Sol:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
   FILE *fp;
   char buff[255];
   int len;
   fp = fopen("test11.txt", "r");
   if(fp==NULL)
   {
   	printf("Unable to open the file\n");
   	return(0);
   }
   while(1)
   {

     fgets(buff, 255,fp); //reads  line by line
    if(feof(fp))
   {
     printf("\n\n\nend of file");
     break;
   }
   len=strlen(buff);
     printf("%s Len: %d\n", buff,len );
   }
   fclose(fp);
   getch();
   return(0);
}

Number Of Visitors

0270452