1. c語言讀寫配置文件
#include <stdio.h>
#include <string.h>
#define MAX_BUF 20
#define SERVER "localhost"
#define CONFIG_FILE "1.conf"
bool SetAuthServer(char* strServerAdd)
{
char buf[MAX_BUF], tempBuf[MAX_BUF];
memset(buf, 0, MAX_BUF);
memset(tempBuf, 0, MAX_BUF);
FILE *pF = fopen(CONFIG_FILE, "r");
if(!pF)
{
printf("打開文件失敗!\n");
return false;
}
fread(buf, MAX_BUF, 1, pF);
if(!feof(pF))
{
printf("讀取不完整,請把MAX_BUF設置為大一點, 當前大小為: %d\n", MAX_BUF);
fclose(pF);
return false;
}
fclose(pF);
char *lpPos = buf;
char *lpNewPos = buf;
while(lpNewPos = strstr(lpPos, SERVER))
{
strncpy(tempBuf+strlen(tempBuf), lpPos, lpNewPos-lpPos);
strcat(tempBuf, strServerAdd);
lpPos = lpNewPos + strlen(SERVER);
}
strcat(tempBuf, lpPos);
pF = fopen(CONFIG_FILE, "w");
if(!pF)
{
printf("打開文件失敗!\n");
return false;
}
fwrite(tempBuf, strlen(tempBuf), 1, pF);
fclose(pF);
return true;
}
void main()
{
char buf[20];
printf("請輸入一個字元串來修改伺服器配置: ");
scanf("%s", buf);
if(SetAuthServer(buf) == true)
printf("修改成功!\n");
else
printf("修改失敗!\n");
}
2. c語言如何解析xml並將所有內容存入數組
/*前段時間恰好做過類似的東西,代碼可以給你參考下。
*Xml配置見最後
*/
typedefstructSrcFileFmt
{
intColID;
charColCode[64];/*欄位英文名稱*/
charColName[128];/*欄位中文名稱*/
charColType[20];/*欄位類型(包含長度)*/
charColComment[128];/*欄位描述*/
}SrcFileFmt;
intmain(intargc,char**argv)
{
SrcFileFmtSrcFileFmt[128];
intiNum=-1;
if(2>argc)
{
printf("Usage:%sSrcXmlFile ",argv[0]);
return-1;
}
iNum=parseSourceCfg(SrcCfgFile,SrcFileFmt);
if(iNum==-1)
{
return-1;
}
return0;
}
/*調用此函數後,xml文件的內容會被存儲到結構體數組SrcFileFmtsrcfilefmt[]中
*此函數依賴於libxml2-2.9.2.tar.xz
*/
intparseSourceCfg(char*FileName,SrcFileFmtsrcfilefmt[])
{/*解析源文件xml,FileName為源xml文件名*/
xmlDocPtrdoc;
xmlNodePtrcur,root;
charsFileName[64]={'