Displaying portion of text from text file in C

297 Views Asked by At

I have a text file and I wanted to extract only a specific part of it at a particular time.For that ,I used ftell() while writing to note the start and end positions and then use fseek() to jump to that particular location.

     int main()
    {
       FILE *fp=fopen("myt","w+");
       char s[80];
       printf ( "\nEnter a few lines of text:\n" ) ;
       while ( strlen ( gets ( s ) ) > 0 )  //user inputs random data
      {                                     //till enter is pressed
       fputs ( s, fp ) ;
       fputs ( "\n", fp ) ;
      }

     long int a=ftell(fp);
     fputs("this line is supposed to be printed only ",fp);//line to be 
                                                           // displayed
     fputs("\n",fp);
     long int b=ftell(fp);
     printf("start is %ld",a);
     printf("\nend is %ld",b);
     printf("here is the data...\n");
     rewind(fp);
     fseek(fp,a,SEEK_CUR);   //move to the starting position of text to be 
                            //displayed
     char x[1000];
     fgets(x,b-a,SEEK_CUR);
     printf("%s",x);
     return 1;
  }

I tried this but face a unexpected abnormal termination of program.Please guide me as to how correctly implement my task.

1

There are 1 best solutions below

4
Jabberwocky On

You want this:

Comments starting with //// are mine

#include <stdio.h>     //// include required header files
#include <string.h>

int main()
{
  FILE *fp = fopen("myt", "w+");

  if (fp == NULL)     //// test if file has been opened sucessfully
  {
    printf("Can't open file\n");
    return 1;         //// return 1 in case of failure
  }

  char s[80];
  printf("\nEnter a few lines of text:\n");
  while (strlen(gets(s)) > 0)  //user inputs random data
  {                                     //till enter is pressed
    fputs(s, fp);
    fputs("\n", fp);
  }

  long int a = ftell(fp);
  fputs("this line is supposed to be printed only ", fp);//line to be 
                                                         // displayed
  fputs("\n", fp);
  long int b = ftell(fp);
  printf("start is %ld", a);
  printf("\nend is %ld", b);
  printf("here is the data...\n");
  rewind(fp);
  fseek(fp, a, SEEK_CUR);   //move to the starting position of text to be 
                            //displayed
  char x[1000];
  fgets(x, sizeof(x), fp); //// the usage of fgets was totally wrong
  printf("%s", x);

  return 0;   //// return 0 in case of success, no one
}

Disclaimer: The first part reading the strings using gets is still sloppy, you should never use gets, it's an old deprecated function. Use fgets instead.