首页 > 其他 > 详细

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

时间:2015-06-12 13:26:17      阅读:317      评论:0      收藏:0      [点我收藏+]

;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;
		}
	}
	if(feof(in) && strlen(temp) != 0)  //如果到了文件尾,写入父节点</>
	{
		fprintf(out,"</%s>",temp);
		fprintf(stdout,"</%s>\n",temp);
	}
	fclose(in);
	fclose(out);

	return 0;
}





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

原文:http://blog.csdn.net/a1232345/article/details/46470153

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!