书上的练习题,把ini文件模式转换成XML格式
来源:互联网 发布:软件评测师证书 编辑:程序博客网 时间:2024/05/03 01:33
#include <stdio.h>#include <string.h>#include <stdbool.h>#include <unistd.h>int main(int argc, char *argv[]){ bool flag = false; char tmp[80]; char st[80]; char name[80], val[80]; FILE *fp, *ofp; char *p; if (argc != 3) { printf("参数不正确\n"); _exit(0); } if ((fp = fopen(argv[1], "r")) == NULL || (ofp = fopen(argv[2], "w")) == NULL) { perror("打开文件出错"); _exit(0); } while (fgets(tmp, 80, fp) != NULL) { char c = 0; sscanf(tmp, " %c", &c); switch(c) { case ';': p = strchr(tmp, '\n'); if (p != NULL) *p = '\0'; printf("<!-- %s -->\n", tmp+1); fprintf(ofp, "<!-- %s -->\n", tmp+1); break; case '[': p = strchr(tmp, ']'); if (p == NULL) printf("error\n"); else { *p = '\0'; flag = true; strcpy(st, tmp+1); } printf("<%s>\n", tmp+1); fprintf(ofp, "<%s>\n", tmp+1); break; case 0: if (flag) { printf("</%s>\n\n", st); fprintf(ofp, "</%s>\n\n", st); flag = false; } break; default : p = strchr(tmp, '='); if (p == NULL) printf("error\n"); else { *p = '\0'; sscanf(tmp, " %s", name); sscanf(p+1, " %s", val); printf("\t<%s>%s</%s>\n", name, val, name); fprintf(ofp, "\t<%s>%s</%s>\n", name, val, name); } } } if (flag) printf("</%s>\n", st); fprintf(ofp, "</%s>\n", st); fclose(fp); fclose(ofp); return 0;}