- 论坛徽章:
- 0
|
20可用积分
求大侠告诉我该怎么改!!!!
1.程序思路:
先从文本文件test中读出内容,放到char tmp[200]中;
读的过程,遇到“name=apple”时,不将它放入tmp[200]中,而是换成“name=banana”;
最后再将tmp[200]的内容写入文本文件test.
2.文本文件test中的内容:
sort=fruits;
name=apple
price=4
3.程序:(程序代码见下,运行在linux下)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define txtfile "test"
int main()
{
FILE *fp, *fp2; char tmp[200];char *line; size_t len; int ret;
//read content form txtfile;
fp=fopen(txtfile,"r");
if(fp == NULL){perror(txtfile);exit(EXIT_FAILURE);}
while ((read = getline(&line, &len, fp)) != -1) {
if(line=="\n")continue;
if(strstr(line,"name=apple"))
strcat(tmp,"name=banana");
else
strcat(tmp,line);
strcat(tmp,"\n");
}
fclose(fp);
//write content from tmp back to txtfile;
fp2 = fopen(txtfile, "w");
if(fp == NULL){perror(txtfile);exit(EXIT_FAILURE);}
ret=fputs(tmp,fp);
if(ret <0||ret==EOF)
printf("Write error!\n");
fclose(fp2);
return 0;
}
4.执行时出现错误:
[apples@dnisw3 test]$ ./a.out
*** glibc detected *** ./a.out: realloc(): invalid pointer: 0x008acfc0 ***
======= Backtrace: =========
/lib/i686/nosegneg/libc.so.6(realloc+0x3ab)[0x91e84b]
/lib/i686/nosegneg/libc.so.6[0x91e991]
/lib/i686/nosegneg/libc.so.6(realloc+0x3c)[0x91e4dc]
/lib/i686/nosegneg/libc.so.6(getdelim+0x16a)[0x90b4ca]
/lib/i686/nosegneg/libc.so.6(getline+0x33)[0x9088c3]
./a.out[0x80485ef]
/lib/i686/nosegneg/libc.so.6(__libc_start_main+0xdc)[0x8c9f2c]
./a.out[0x8048461]
======= Memory map: ========
00893000-008ac000 r-xp 00000000 08:01 7997060 /lib/ld-2.5.so
008ac000-008ad000 r--p 00018000 08:01 7997060 /lib/ld-2.5.so
008ad000-008ae000 rw-p 00019000 08:01 7997060 /lib/ld-2.5.so
008b4000-009ef000 r-xp 00000000 08:01 7997061 /lib/i686/nosegneg/libc-2.5.so
009ef000-009f1000 r--p 0013a000 08:01 7997061 /lib/i686/nosegneg/libc-2.5.so
009f1000-009f2000 rw-p 0013c000 08:01 7997061 /lib/i686/nosegneg/libc-2.5.so
009f2000-009f5000 rw-p 009f2000 00:00 0
00a98000-00a99000 r-xp 00a98000 00:00 0 [vdso]
00c9e000-00ca9000 r-xp 00000000 08:01 7997070 /lib/libgcc_s-4.1.1-20061011.so.1
00ca9000-00caa000 rw-p 0000a000 08:01 7997070 /lib/libgcc_s-4.1.1-20061011.so.1
08048000-08049000 r-xp 00000000 08:03 24414215 /home/apples/test/a.out
08049000-0804a000 rw-p 00000000 08:03 24414215 /home/apples/test/a.out
0903c000-0905d000 rw-p 0903c000 00:00 0
b7ef1000-b7ef2000 rw-p b7ef1000 00:00 0
b7f0d000-b7f0f000 rw-p b7f0d000 00:00 0
bfd49000-bfd5f000 rw-p bfd49000 00:00 0 [stack]
Aborted |
|