我已经制作了(几乎)一个将完整行打印到文件中的程序(除非您按Enter键);请看看它:为什么写入文件时字符会加倍(uupp)?
#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我在这里”,在控制台会在文件打印这样的:
hheelloo wwoorrlldd ii aamm hheerree
指每个角色两次。请找出错误。我非常困惑。同时告诉我是否需要释放两个指针,即line
和exline
?是不是还好只此
free(exline);//as exline is pointing to the complete buffer
你确实喜欢做尽可能复杂的事情,呵呵? – MightyPork
@MightyPork是吗? – YakRangi
我建议通过一个调试器,看着你在做什么... – geoffspear