加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 06:17:33 所属栏目:百科 来源:网络整理
导读:;Configuration of http[http]domain=www.mysite.comport=8080cgihome=/cgi-bin;Configuration of db[database]server = mysqluser = mynamepassword = toopendatabase 一个配置文件由若干个Section组成,由[]括号括起来的是Section名。每个Section下面有若

;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] = {''};
	char *key,*value;
	char *ch;
	int i;

	if(argc < 3)
	{
		printf("Usage: name.ini name.xmln");
		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 = '';

		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 = '';
			fprintf(out,"<%s>n",&buf[i+1]);
			strcpy(temp,&buf[i+1]);
			break;
		case '':  //空行
			if(strlen(temp) != 0)
			{
				fprintf(out,"</%s>n",temp);
				fprintf(stdout,temp);
			}
			memset(temp,'',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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读