求向文本文件中插入字符串 C语言

来源:百度知道 编辑:UC知道 时间:2024/09/21 18:12:39
比如有一个文本文件内容如下
<name>
12345
</name>
需要程序在执行完以后,成为
<name>
12345
54321
</name>
看到有种方法是先读出要插入的位置以后的内容到内存中备份的,具体是怎么实现的呢,麻烦帮忙写段源程序,分少,请好人帮忙,非常感谢!!

#include <stdio.h>
#include <stdlib.h>

FILE *fin,*fout;
void main()
{
int z;
int c[100];
int i,L;
fin = fopen("a1.txt","r");
fout = fopen("a2.txt","w");
while ( (z = fgetc(fin)) != '>'){
fputc(z,fout);
}
fputc(z,fout);

L= 0;
while ( (z = fgetc(fin)) != '<'){
if (L !=0) fputc(z,fout);
c[L] = z;
L++;
}

L = L - 1;
for (i=L-2;i>0;i--) fputc(c[i],fout);
fputc(z,fout);
while ( (z = fgetc(fin)) != EOF){
fputc(z,fout);
}
fclose(fin); fclose(fout);
printf("output in a2.txt\n");
exit(0);
}

要点:1.打开文件
2.读取12345保存到string字符串变量
3.反转字符串
4.定位到文件尾
5.变量输出到文件
6.关闭文件
至于代码可以根据上面的要点去查看相关的知识点.对你的知识强化有帮助.