配置檔案讀寫案例

2021-09-12 12:30:32 字數 3126 閱讀 5007

//從左往右移動,如果當前字元為空,而且沒有結束

while (isspace(p[begin]) && p[begin] != 0)

while (isspace(p[end]) && end > 0 )

if (end == 0)

n = end - begin + 1;//非空元素個數

strncpy(outbuf, p + begin, n);

outbuf[n] = 0;

return 0;

}int readcfgfile(char *file, char *key, char *value, int *len)

file *fp = null;

int ret = 0;

char linebuf[1024] = ;

char *p = null;

int flag = 0; //0表示沒有找到

//開啟檔案

fp = fopen(file, "r+");

if (fp == null)

while (1)

//linebuf == "k1 = abc"

//找key

p = strstr(linebuf, key);

if (p == null) //沒有

//重新設定起點

p = p + strlen(key);

//找 "="

p = strstr(p, "=");

if (p == null) //沒有

//重新設定起點

p = p + strlen("=");

//獲取非空字元

ret = trimspace(p, value);

if (ret == 0)//成功

else

}end:

if (fp != null)

if (flag == 0)

return ret;

}int writecfgfile(char *file, char *key, char *value, int len)

file *fp = null;

int ret = 0;

char linebuf[1024] = ;

char buf[size] = ;

char *p = null;

int flag = 0; //0表示沒有找到

fp = fopen(file, "r+");

if (fp == null) //開啟失敗,有可能是配置檔案沒有建立 }

//獲取檔案大小

//游標移動到結尾

fseek(fp, 0, seek_end);

long size = ftell(fp);

if (size >= size)

//游標回到檔案開頭

rewind(fp);

while (1)

//每一行是否包含key

if (strstr(linebuf, key) != null)

else

}//程式到這,2種情況

if (0 == flag) //沒有key

else //有key

fp = fopen(file, "w+");

if (fp == null)

//重新寫內容

fputs(buf, fp);

}end:

if (fp != null)

return ret;

}

#define _crt_secure_no_warnings

#include #include #include #include "cfg.h"

#define cfgname "mycfg.ini"

void menu()

void myread()

; char value[1024] = ;

int len = 0;

int ret = 0;

printf("請輸入key值:");

scanf("%s", key);

ret = readcfgfile(cfgname, key, value, &len);

if (ret != 0)

printf("\n%s對應的value:%s, len = %d\n", key, value, len);

}void mywrite()

; char value[1024] = ;

int len = 0;

int ret = 0;

printf("請輸入key值:");

scanf("%s", key);

printf("請輸入value值:");

scanf("%s", value);

ret = writecfgfile(cfgname, key, value, strlen(value));

if (ret != 0)

printf("\n寫入成功,輸入的是:%s對應的value:%s, len = %d\n", key, value, strlen(value));

}int main(void)

} printf("\n");

system("pause");

return 0;

}

讀寫配置檔案

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...