2014-03-29 40 views
0

我已经制作了(几乎)一个将完整行打印到文件中的程序(除非您按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 

指每个角色两次。请找出错误。我非常困惑。同时告诉我是否需要释放两个指针,即lineexline?是不是还好只此

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

你确实喜欢做尽可能复杂的事情,呵呵? – MightyPork

+0

@MightyPork是吗? – YakRangi

+1

我建议通过一个调试器,看着你在做什么... – geoffspear

回答

2

你先做

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

然后

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

这是把字符两次到line

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

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

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

这也将解决额外realloc ations超越了前100个字符。

+0

thanxx男人我只是想通了。但关于免费()我的第二个问题呢? – YakRangi

+0

现在我已经纠正它,但仍然当我输入超过100个字符程序崩溃,请找出它? – YakRangi

+0

exline = realloc(exline,lenmax + = 100)是危险的,就像realloc()失败一样,它会返回NULL,并将其分配给exline并导致内存泄漏。 – YakRangi

相关问题