一个将配置文件转换成xml的示例程序
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char*p;
char buf1[256];
char buf2[256];
char *c;
int len=0;
FILE*fp1,*fp2;
fp1=fopen("z.txt","r");
fp2=fopen("x.xml","w");
while(fgets(buf1,256,fp1)!=NULL)
{
if(buf1[0]=='#')
{
len=strlen(buf1);
buf1[len-1]='\0';
buf1[len-1]='\0';
fprintf(fp2,"<!-----%s----->\n",buf1+1);
}
else if(buf1[0]=='!')
{
len=strlen(buf1);
buf1[len-1]='\0';
strcpy(buf2,buf1);
fprintf(fp2,"<%s>\n",buf1+1);
}
else if(buf1[0]=='\n')
{
fprintf(fp2,"<%s>\n",buf2+1);
}
else
{
len=strlen(buf1);
buf1[len-1]='\0';
p=buf1;
c=strsep(&p,"=");
fprintf(fp2,"<%s>",c);
fflush(fp2);
fprintf(fp2,"%s",p);
fflush(fp2);
fprintf(fp2,"</%s>\n",c);
}
}
return 0;
}
z.txt如下:
[y@YMY C]$ cat z.txt
#config of network
!network
ip=192.168.11.6
port=8000
home-path=/home/admin/
#config of database
!database
server=mySQL
user=admin
password=133432
运行结果:
[y@YMY C]$ gcc b.c
[y@YMY C]$ ./a.out
[y@YMY C]$ cat x.xml
<!-----config of network----->
<network>
<ip>192.168.11.6</ip>
<port>8000</port>
<home-path>/home/admin/</home-path>
<network>
<!-----config of database----->
<database>
<server>mySQL</server>
<user>admin</user>
<password>133432</password>
<database>
[y@YMY C]$