【练习题】编程把INI文件转换成XML文件

;Configuration of http
[http]
domain=www.mysite.com
port=8080
cgihome=/cgi-bin

;Configuration of db
[database]
server = mysql
user = myname
password = toopendatabase

一个配置文件由若干个Section组成,由[]括号括起来的是Section名。每个Section下面有若干个key = value形式的键值对( Key-value Pair) ,等号两边可以有零个或多个空白字符(空格或Tab),每个键值对占一行。以;号开头的行是注释。每个Section结束时有一个或多个空行,空行是仅包含零个或多个空白字符(空格或Tab)的行。 INI文件的最后一行后面可能有换行符也可能没有。

<!-- Configuration of http -->
<http>
        <domain>www.mysite.com</domain>
        <port>8080</port>
        <cgihome>/cgi-bin</cgihome>
</http>

<!-- Configuration of db -->
<database>
        <server>mysql</server>
        <user>myname</user>
        <password>toopendatabase</password>
</database>

程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
	FILE *in, *out;
	char buf[1024];
	char temp[1024] = {'\0'};
	char *key, *value;
	char *ch;
	int i;

	if(argc < 3)
	{
		printf("Usage: name.ini name.xml\n");
		exit(1);
	}

	in = fopen(argv[1],"r");
	if(in == NULL)
	{
		perror("open ini file");
		exit(1);
	}
	out = fopen(argv[2],"w+");
	if(out == NULL)
	{
		perror("open xml file");
		exit(1);
	}
	
	while(fgets(buf,sizeof(buf),in) != NULL)
	{
		i = 0;
		//skip blank character
		while(buf[i] == '\t' || buf[i] == ' ')
		{
			i++;
			continue;
		}
		ch = strchr(buf+i,'\n');  //去除换行符
		if(ch != NULL)
			*ch = '\0';

		switch(buf[i])
		{
		case ';':
			fprintf(out,"<!-- %s -->\n",&buf[i+1]);
			fprintf(stdout,"<!-- %s -->\n",&buf[i+1]);
			break;
		case '[':
			ch = strchr(buf+i,']');
			if(ch != NULL)
				*ch = '\0';
			fprintf(out,"<%s>\n",&buf[i+1]);
			fprintf(stdout,"<%s>\n",&buf[i+1]);
			strcpy(temp,&buf[i+1]);
			break;
		case '\0':  //空行
			if(strlen(temp) != 0)
			{
				fprintf(out,"</%s>\n",temp);
				fprintf(stdout,"</%s>\n",temp);
			}
			memset(temp,'\0',sizeof(temp));
			fprintf(out,"\n");
			fprintf(stdout,"\n");
			break;
		default:
			key = strtok(&buf[i],"= ");
			value = strtok(NULL,"= ");
			fprintf(out,"\t<%s>%s</%s>\n",key,value,key);
			fprintf(stdout,"\t<%s>%s</%s>\n",key,value,key);
			break;
		}
	}
<span style="white-space:pre">	<span style="font-family:Courier New;font-size:18px;color:#008000;orphans: 2; widows: 2;"><span style="font-size: 15pt;"></span></span>//如果到了文件尾,写入父节点的最后一个tag</></span>,<span style="white-space:pre">strlen(temp) != 0排除最后一行有换行符时,多余的</>写入<span style="orphans: 2; widows: 2; font-size: 15pt; color: rgb(0, 128, 0); font-family: 'Courier New';"></span></span>
	if(feof(in) && strlen(temp) != 0)  
	{
		fprintf(out,"</%s>",temp);
		fprintf(stdout,"</%s>\n",temp);
	}
	fclose(in);
	fclose(out);

	return 0;
}





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值