;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; }
时间: 2024-10-17 10:45:33