gpt4 book ai didi

c - 读取未知大小的文本文件

转载 作者:太空狗 更新时间:2023-10-29 17:02:55 24 4
gpt4 key购买 nike

我正在尝试将一个未知大小的文本文件读入一个字符数组。这是我目前所拥有的。

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

int main()
{
FILE *ptr_file;
char buf[1000];
char output[];
ptr_file =fopen("CodeSV.txt","r");
if (!ptr_file)
return 1;

while (fgets(buf,1000, ptr_file)!=NULL)
strcat(output, buf);
printf("%s",output);

fclose(ptr_file);

printf("%s",output);
return 0;
}

但是当我读取一个未知大小的文件时,我不知道如何为输出数组分配一个大小。此外,当我为输出输入一个大小时,比如 n=1000,我得到了段错误。我是一个非常没有经验的程序员任何指导表示赞赏:)

文本文件本身在技术上是一个 .csv 文件,因此内容如下所示:“0,0,0,1,0,1,0,1,1,0,1...”

最佳答案

这样做的标准方法是使用 malloc 分配一个一定大小的数组,然后开始读入它,如果在用完字符之前用完数组(即,如果在填充数组之前没有达到 EOF),请为数组选择更大的大小并使用 realloc 使其更大。

这是读取和分配循环的样子。我选择使用 getchar 一次读取输入一个字符(而不是使用 fgets 一次读取一行)。

int c;
int nch = 0;
int size = 10;
char *buf = malloc(size);
if(buf == NULL)
{
fprintf(stderr, "out of memory\n");
exit(1);
}

while((c = getchar()) != EOF)
{
if(nch >= size-1)
{
/* time to make it bigger */
size += 10;
buf = realloc(buf, size);
if(buf == NULL)
{
fprintf(stderr, "out of memory\n");
exit(1);
}
}

buf[nch++] = c;
}

buf[nch++] = '\0';

printf("\"%s\"", buf);

关于这段代码的两个注意事项:

  1. 初始大小和增量的数字 10 太小了;在实际代码中,您可能希望使用更大的东西。
  2. 很容易忘记确保尾随的“\0”有空间;在这段代码中,我尝试使用 if(nch >= size-1) 中的 -1 来做到这一点。

关于c - 读取未知大小的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31057175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com