讀寫配置檔案

2022-03-19 09:45:15 字數 3078 閱讀 6899

配置檔案讀寫系統方法和測試函式

#include"

readconfig.h

"#define cfgname "./test.txt"

void

mymenu()

inttgetcfg()

;

char value[1024] = ;

int vlen = 0

; printf(

"\nplease input key: ");

scanf(

"%s,

",name);

ret = getcfgitem(cfgname, name, value, &vlen);

if (0 !=ret)

printf(

"value:%s \n

",value);

return

ret;

}int

twritecfg()

;

char value[1024] = ;

printf(

"\nplease input key: ");

scanf("%s

",name);

printf(

"\nplease input value: ");

scanf("%s

", value);

ret =writecfgitem(cfgname, name, value, strlen(value));

if (0 !=ret)

printf(

"your input name is %s , value is %s\n

", name, value);

return

ret;

}int

main()

}printf(

"end......");

return0;

}

/*

readconfig.h

*/#ifndef _readconfig_h__

#define _readconfig_h__#include

#include

#include

#define maxline 2048#ifdef __cplusplus

extern"c

"#endif

#endif

/*

readconfig.c

*/#include

"readconfig.h"//

獲取配置項

int getcfgitem(char *pfilename, char *pkey, char *pvalue, int *pvaluelen)

while (!feof(fp))

ptmp = strstr(linebuf, pkey); //

判斷該行是否有pkey

if (ptmp ==null)

ptmp = ptmp + strlen(pkey); //

wang = qing ==> "= qing"

ptmp = strchr(ptmp, '

='); //

判斷pkey後面是否有=

if (ptmp ==null)

ptmp = ptmp + 1; //

有等號把指標移到 = 號後一位

//獲取value的起點 去除空格,遇到第乙個非空格符號位置賦予pbegin

while(1

)

else

break

; }

}//獲取value終點

//遇到換行符或空格符終止(value值中不能有換行符空格符)

while(1

)

else

}pend =ptmp;

*pvaluelen = pend -pbegin;

memcpy(pvalue, pbegin, pend-pbegin);

}if (fp !=null)

return0;

}/*寫配置檔案

迴圈寫每一行,檢查key配置項是否存在,若存在,則修改對應value值

若不存在,則在檔案末尾新增 「key = value」

*/int writecfgitem(char *pfilename, char *pkey, char *pvalue, int

valuelen)

;

if (pfilename == null || pkey == null || pvalue ==null)

fp = fopen(pfilename, "r+"

);

if (fp ==null)

}fseek(fp,

0l, seek_end); //

把檔案指標從檔案開頭移動到檔案結尾

length = ftell(fp); //

獲取檔案長度

if (length > 1024 *8

)

fseek(fp,

0l, seek_set);

while (!feof(fp))

/*檢查pkey是否在本行

不在copy到filebuf中

在先修改,copy到filebuf中(替換)

讀完整個檔案

*/ptmp =strstr(linebuf, pkey);

if (ptmp ==null)

else

}//關鍵字不存在,追加

if (itag == 0

)

else

//若關鍵字存在,則重新建立檔案 先關閉原始檔,再重新從頭寫入該檔案中

fp = fopen(pfilename, "

w+t"

);

if (fp ==null)

}fputs(filebuf, fp);

}if (fp !=null)

return

rv;}

讀寫配置檔案

windows作業系統專門為此提供了6個api函式來對配置設定檔案進行讀 寫 getprivateprofileint 從私有初始化檔案獲取整型數值 getprivateprofilestring 從私有初始化檔案獲取字串型值 getprofileint 從win.ini 獲取整數值 getprof...

讀寫配置檔案

procedure curstepchanged curstep tsetupstep varsetupname string inipath string begin case curstep of ssinstall 複製檔案前 begin end sspostinstall 完成複製 begi...

讀寫配置檔案

寫配置檔案 include include include include using std cout using std endl int main int nlen strlen d myinifile.ini 16 nlen strlen lppath 0 strcpy s lppath,s...