读取文件的特定部分时出现问题

时间:2017-11-20 08:40:22

标签: c arrays fopen file-handling fseek

我试图在给定时间从文件中提取和打印特定部分的文本。我使用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
  }

我尝试使用这种方法,但程序只打印第一行。输出如下:

         this line is supposed to be printed only

我想要打印两条打印线。请建议一种方法。

1 个答案:

答案 0 :(得分:1)

我认为你对阅读部分的意图是

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

注意:

  • 我为缓冲区x的分配添加了+1,因为fgets添加了 null终止。

  • 我并非100%确定您在写入和读取之间不想要fflush(fp)