【发布时间】:2016-04-18 23:43:53
【问题描述】:
int main()
{
//FILE *out = fopen("keimeno.txt", "w+");
FILE *in = fopen("keimeno.txt", "r");
int fullbufflen=0 , i;
char buffer[100];
fgets(buffer, 100, in);
int bufflen = strlen(buffer);
char *text;
text =calloc(bufflen,sizeof(char));
char *strcat(text, buffer);
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
fullbufflen = bufflen;
while(fgets(buffer, 100, in)!=NULL)
{
// printf("line of \"keimeno.txt\": %s", buffer);
// printf("size of line \"keimeno.txt\": %i\n\n", bufflen);
text =realloc(text,bufflen*sizeof(char));
char *strcat(text, buffer);
fullbufflen = bufflen + fullbufflen ;
}
for (i = 0;i<fullbufflen;i++)
{
printf("%c\n",text[i]);
}
}
我正在尝试将全文文件 (keimeno.txt) 复制到动态内存数组中,每次最多使用 100 个字符的缓冲区。最后为了测试它,我试图打印结果。我就是不能让它工作。不知道是不是最后的printf有问题,还是整个程序出错了。
此外,动态数组在开始时应该有 0 大小,所以如果有人也能告诉我该怎么做,那将是受欢迎的。
提前致谢。
【问题讨论】:
-
char *strcat(text, buffer);行是什么? -
您的
calloc()2 是错误的。 1. 您需要为终止nul字节分配1 个额外字节。 2. 你不需要calloc()你需要malloc()。
标签: c file dynamic malloc realloc