读取文件特定部分的问题

Issue in reading specific portion of File

我正在尝试从给定的文件中提取并打印文本的特定部分 time.I 使用 ftell() 和 fseek() 来实现此目的。

     #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);

    fputs("this line is also to be printed\n",fp);         //line to be 
                                                           //displayed
    fputs("\n",fp);

    long int b = ftell(fp);

    fputs("this is scrap line",fp);
    fputs("\n",fp);

    rewind(fp);
    fseek(fp, a, SEEK_CUR);  //move to the starting position of text to be
                             //displayed

    long int c=b-a;          //no of characters to be read
    char x[c];
    fgets(x, sizeof(x), fp); 
    printf("%s", x);

   fclose(fp);

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

我尝试使用这种方法,但程序只打印第一个 line.The 输出如下:

         this line is supposed to be printed only

我想打印这两行 printed.Please 建议一种方法。

我认为您阅读部分的意图是

rewind(fp);
fseek(fp, a, SEEK_CUR);  //move to the starting position of text to be
                         //displayed

long int c=b-a;          //no of characters to be read
char x[c+1];

int used = 0;
while(ftell(fp) < b)
{
  fgets(x+used, sizeof(x)-used, fp);
  used = strlen(x);
}
printf("%s", x);

备注:

  • 我在您的缓冲区分配中添加了 +1 x 因为 fgets 添加了 空终止。

  • 我不能 100% 确定您不希望 fflush(fp) 在写入和读取之间。