在C中显示文本文件的部分文本

时间:2017-11-14 14:06:37

标签: c file file-handling fseek ftell

我有一个文本文件,我想在特定时间只提取它的一个特定部分。为此,我在编写时使用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;
  }

我尝试了这个,但面对一个意外的异常终止程序。请指导我如何正确实现我的任务。

1 个答案:

答案 0 :(得分: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