0

我有一个文本文件,我想在特定时间只提取其中的特定部分。为此,我在写作时使用 ftell() 记录开始和结束位置,然后使用 fseek() 跳转到该特定位置.

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

我试过这个,但遇到程序意外异常终止。请指导我如何正确执行我的任务。

4

1 回答 1

1

你要这个:

////以是我的开头的评论

#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
}

免责声明:使用读取字符串的第一部分gets仍然很草率,你永远不应该使用gets,它是一个旧的不推荐使用的函数。改为使用fgets

于 2017-11-14T14:31:18.427 回答