【问题标题】:Issue in reading specific portion of File读取文件特定部分的问题
【发布时间】:2017-11-20 08:40:22
【问题描述】:

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

我想打印要打印的两行。请提出一种方法。

【问题讨论】:

  • fgets() 读取一行(在换行处停止)。要么多次调用fgets(),要么只使用fread()读取给定数量的数据。
  • 由于这与您的实际问题无关,因此我投票将其作为“简单的错字”结束。
  • 有人可以帮我写一段代码吗?我是新手,需要帮助
  • +Felix Palmen 我已更正标题。请撤下您的投票
  • 我刚刚向您解释了您的问题是什么,这是对fgets() 的错误假设。同样,fgets() 在第一个换行符处停止阅读。你还需要什么来解决这个问题? :o

标签: c arrays fopen file-handling fseek


【解决方案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);

注意事项:

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

  • 我不是 100% 确定您不想在写入和读取之间使用fflush(fp)

【讨论】:

  • 这里,使用fread() 的方法会更简单、更高效。
  • 同意一个警告:他以文本模式打开文件。 IIRC,文本模式下 ftell 和 fread 之间的关系很脆弱。 (我认为 ftell 跟踪所有字节,折叠 CRLF 后的 fread 计数)
  • 在以文本模式打开的文件上,从ftell() 结果计算 sizes 通常会出现问题。
  • 这里的“安全”事情是(如果它必须是文本文件)根本不计算大小并使用fgets(),计算行数相反...
  • 同意这是一个更好的解决方案
猜你喜欢
  • 1970-01-01
  • 2013-09-13
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
相关资源
最近更新 更多