最近写了一个用Mini-XML写XML小程序,读取原来XML内容然后进行修改。
但是发现每次写XML时,没有将原来的文件内容全部清除,只是将新的内容覆盖上去。
纠结了N久才以为是用了fopen函数,fopen是带缓冲的,没有清理文件缓冲就写文件是不行的。
加上fflush(fp)或 flushall(),问题还是没解决!!
目前笨拙方法是,先以读方式读出,关闭文件,再以写方式写入新内容。
求助~~
#include <mxml.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
FILE *fp;
mxml_node_t *tree;
mxml_node_t *node;
char* szAttr;
fp = fopen(argv[1], "r+");
if (NULL == fp)
{
printf("Error:Open file '%s' failed!\n", argv[1]);
return -1;
}
tree = mxmlLoadFile(NULL, fp, MXML_TEXT_CALLBACK);
if ( NULL == tree )
{
printf("Error: Load xml failed!\n");
fclose(fp);
return -1;
}
node = mxmlFindElement(tree, tree, "node", NULL,
NULL, MXML_DESCEND);
if ( NULL == node )
{
printf("Error: Can't find node!\n");
fclose(fp);
return -1;
}
if ( 0==mxmlSetText(node, 0, "10.0") )
{
printf("Set text successfully!\n");
}
else
{
printf("Error:Set text failed!\n");
}
/*node = mxmlFindElement(tree, tree, "node", NULL, NULL, MXML_DESCEND);
for ( ;node != NULL; node = mxmlFindElement(node, tree, "node", NULL, NULL, MXML_DESCEND))
{
}*/
/*
fclose(fp);
fp = fopen(argv[1], "w");
if (NULL == fp)
{
printf("Error:Open file '%s' failed!\n", argv[1]);
return -1;
}*/
fflush(fp);
if ( 0==mxmlSaveFile(tree, fp, MXML_NO_CALLBACK) )
{
printf("Save xml successfully!\n");
}
else
{
printf("Error:Save xml failed!\n");
}
fclose(fp);
return 0;
}