首页 > 解决方案 > 尝试使用 fgetc() 从文件中读取未知字符串长度

问题描述

所以,是的,看到了许多与此类似的问题,但想尝试以我的方式解决它。运行后获得大量文本块(编译良好)。

我试图从文件中获取未知大小的字符串。考虑以 2 的大小分配 pts(1 个字符和空终止符),然后使用 malloc 为每个超过数组大小的字符增加 char 数组的大小。

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

int main()
{
    char *pts = NULL;
    int temp = 0;

    pts = malloc(2 * sizeof(char));
    FILE *fp = fopen("txtfile", "r");
    while (fgetc(fp) != EOF) {
        if (strlen(pts) == temp) {
            pts = realloc(pts, sizeof(char));
        }
        pts[temp] = fgetc(fp);
        temp++;
    }

    printf("the full string is a s follows : %s\n", pts);
    free(pts);
    fclose(fp);

    return 0;
}

标签: cstringfilestring-lengthfgetc

解决方案


你可能想要这样的东西:

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

#define CHUNK_SIZE 1000               // initial buffer size

int main()
{
  int ch;                             // you need int, not char for EOF
  int size = CHUNK_SIZE;

  char *pts = malloc(CHUNK_SIZE);
  FILE* fp = fopen("txtfile", "r");

  int i = 0;
  while ((ch = fgetc(fp)) != EOF)     // read one char until EOF 
  {
    pts[i++] = ch;                    // add char into buffer

    if (i == size + CHUNK_SIZE)       // if buffer full ...
    {
      size += CHUNK_SIZE;             // increase buffer size
      pts = realloc(pts, size);       // reallocate new size
    }
  }

  pts[i] = 0;                        // add NUL terminator

  printf("the full string is a s follows : %s\n", pts);
  free(pts);
  fclose(fp);

  return 0;
}

免责声明:

  1. 这是未经测试的代码,它可能不起作用,但它显示了这个想法
  2. 为了简洁起见,绝对没有错误检查,您应该添加它。
  3. 还有其他改进的空间,它可能可以做得更优雅

推荐阅读