我正在尝试将未知大小的文本文件读入字符数组。到目前为止,这就是我所拥有的。
#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
in做到这一点if(nch >= size-1)
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句