繁体   English   中英

文件的ReadLine函数

[英]ReadLine function for a file

我想要readline的相同功能但是对于文件。 我不想传递缓冲区和大小。 我想要一种方法来malloc适当的空间

使用fgetc ,您可以一次从文件读取一个字符。

因此,您可以通过多次调用fgetc来创建一个逐行读取文件的函数。 如果一行结束,则fgetc读取\\n 如果文件结束,则显示EOF

现在,您执行以下操作:在开头创建一个char line[1024] (分别是通过malloc创建的char* )(或任何其他大小),并填写以下任一情况:

  • fgetc得到\\n :这意味着,当前行结束了,你完成了这一行。
  • fgetc得到EOF :这意味着整个文件都结束了,您已经完成了。
  • fgetc得到任何东西,仍然存在可用空间line :那你简单地复制读取到合适的位置的字符line
  • fgetc得到别的和line已经完全填满:那么,你realloc新内存line和成长的电流line (更具体的,实际的做法是扩大一倍line在此步骤)。

所以基本上你需要告诉自己fgetcrealloc并结合这两个函数(和一些辅助函数)来获得你想要的东西。

这是我以前用过的解决方案。 它将从文本文件中读取一行,直到换行为止。 它首先读取固定大小的本地缓冲区,然后将该缓冲区追加到结果中。

当我们看到换行符或EOF或输入出现错误时,阅读结束。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define PAGE_SIZE ...  // some size large enough to handle most cases

char *getLine(FILE *stream)
{
  char *res = NULL; 
  char inbuf[PAGE_SIZE];
  size_t len = 0;

  /**
   * We want to use strcpy the first time through the loop,
   * then strcat afterward.  Using a function pointer means
   * we don't have to execute a test each time through the 
   * loop.  For a sane text file where individual lines aren't
   * more than a few dozen characters long, this really doesn't
   * buy us anything over an if-else statement; I just think it's a cool trick.
   *
   * For C99, the prototype should be
   *
   *    char *(*f)(char * restrict, const char * restrict)
   */
  char *(*f)(char *, const char *) = strcpy;

  while (fgets(inbuf, sizeof inbuf, stream))
  {
    char *tmp = realloc(res, len + strlen(inbuf) + 1);
    if (tmp)
    {
      res = tmp;
      f(res, inbuf);
      f = strcat;
      len += strlen(inbuf) + 1;
    }
    if (strchr(inbuf, '\n'))
      break;
  }
  if (feof(stream))
    // hit EOF
  else
    // error on read; how you deal with it is up to you.
  return res;
}

请注意,如果我们在初始读取时遇到EOF或错误,则该函数将返回NULL

完成每一行后,您将需要free它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM