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

前端之家收集整理的这篇文章主要介绍了【练习题】编程把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,&buf[i+1]);
			break;
		case '[':
			ch = strchr(buf+i,']');
			if(ch != NULL)
				*ch = '\0';
			fprintf(out,"<%s>\n",&buf[i+1]);
			strcpy(temp,&buf[i+1]);
			break;
		case '\0':  //空行
			if(strlen(temp) != 0)
			{
				fprintf(out,"</%s>\n",temp);
				fprintf(stdout,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,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,temp);
	}
	fclose(in);
	fclose(out);

	return 0;
}

猜你在找的XML相关文章