gpt4 book ai didi

c - 为什么写入文件时字符会加倍 (uupp)?

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:12 24 4
gpt4 key购买 nike

我已经(几乎)制作了一个将完整行打印到文件中的程序(除非您按回车键);请看一下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void getline ( FILE *filep){
char c;int word = 100,lenmax=100;
char *line = (char *)malloc (100),*exline,*save = line;
printf("enter the data to be written press only enter at the end of the paragraph\n");
while(1){
c = fgetc ( stdin );

if ( --word != 0){
*line++ = c;
}
else{
word = 100;
exline = realloc(save ,lenmax += 100);
if (exline == NULL){
free ( line);
exit(1);
}
line = exline + (lenmax-100);
}

if ( (*line++=c)=='\n'){
*line = '\0';
break;
}

}
fprintf(filep,"%s",save);
free(line);
free(exline);
}

int main(){
FILE *fp;
fp = fopen("beauty.txt","w");
getline(fp);
return 1;
}

问题 例如,如果你写“hello world i am here”,在控制台它会像这样打印在文件上:

hheelloo wwoorrlldd ii aamm hheerree

表示每个字符出现两次。请找出错误。我很困惑。还告诉我是否有必要释放两个指针,即 lineexline?只有这个不行吗

free(exline);//as exline is pointing to the complete buffer

最佳答案

你先做

if ( --word != 0){
*line++ = c;
}

然后

if ( (*line++=c)=='\n'){
*line = '\0';
break;
}

将字符两次放入

不要同时释放lineexline,因为当你realloc , line 不再有效。此外,exline 可能根本不会被初始化,只要您保持在 100 个字符以下。最后,您在读取字符时修改了 line,因此无论如何它都不是有效的堆指针。您可以保存变量 save 并只使用 exline。所以正确的方法可能是

char *line = malloc (100), *exline = line;
/* ... */
save = exline;
exline = realloc(save, lenmax += 100);
if (exline == NULL) {
free(save);

/* ... */
free(exline);

这还将修复前 100 个字符之外的额外重新分配

关于c - 为什么写入文件时字符会加倍 (uupp)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22731405/

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