一个ini文件转换xml文件的源码
应该有更好的算法。有什么需要改进的地方 求指教程序代码:
#include<stdio.h> int main(void) { FILE *ini_f,*xml_f; int n, note_flag, sec_flag, key_flag, val_flag, first_key, first_sec, sec, i, j; note_flag = sec_flag = key_flag = val_flag = first_key = first_sec = sec = i = n =0; long read_adr, now_adr; int sec_str[20], str[20]; int tmp[20]; if((ini_f = fopen("001.txt","r")) == NULL){ printf("error open 001.txt file\n"); } if((xml_f = fopen("xml.txt","w")) == NULL){ printf("error open xml.txt file\n"); } while((n = fgetc(ini_f)) != EOF){ //------------------------------------------ if(';' == n){ note_flag = 1; fprintf(xml_f,"<!-- "); key_flag = 0; continue; } if('[' == n){ if(first_sec){ now_adr = ftell(xml_f); fseek(xml_f, read_adr,SEEK_SET ); fprintf(xml_f, "\n</"); for(j=0; j<sec; j++) fputc(sec_str[j], xml_f); fprintf(xml_f, ">\n"); fseek(xml_f, now_adr, SEEK_SET); sec = 0; } sec_flag =1; fprintf(xml_f, "<"); first_sec =1; continue; } if(note_flag){ if('\n' == n){ fprintf(xml_f, " -->"); note_flag = 0; } } //--------------------------------------------------------- if(sec_flag){ if(']' != n){ if((n >= 'a' && n <= 'z') ||( n <= 'Z' && n >= 'A')){ sec_str[sec] = n; sec++; } } if(']' == n){ fprintf(xml_f, ">\n"); sec_flag = 0; key_flag = 1; first_key = 1; continue; } } if(key_flag){ if(val_flag){ if('\n' == n){ fprintf(xml_f, "</"); for(j=0; j<i; j++) fputc(str[j], xml_f); fprintf(xml_f, ">"); val_flag = 0; read_adr = ftell(xml_f); fprintf(xml_f," \n"); i = 0; first_key = 1; continue; } fputc(n, xml_f); } if('=' == n){ first_key =0; fprintf(xml_f, "\t<"); for(j=0; j<i; j++){ fputc(str[j], xml_f); } fprintf(xml_f, ">"); val_flag = 1; } if(first_key){ if((n >= 'a' && n <= 'z') ||( n <= 'Z' && n >= 'A')){ str[i] = n; i++; } } continue; } fputc(n, xml_f); } fprintf(xml_f, "</"); for(j=0; j<sec; j++) fputc(sec_str[j], xml_f); fprintf(xml_f, ">\n"); fclose(xml_f); fclose(ini_f); }以下是一个ini文件
程序代码:
;Configuration of http [http] domain=www.8080 cgihome=/cgi-bin ;Configuration of db [database] server =mysql user = myname password = toopendatabase转换之后的xml文件
程序代码:
<!-- Configuration of http --> <http> <domain>www. <port>8080</port> <cgihome>/cgi-bin</cgihome> </http> <!-- Configuration of db --> <database> <server>mysql</server> <user> myname</user> <password> toopendatabase</password> </database>
[ 本帖最后由 深渊叹息 于 2012-5-16 22:03 编辑 ]