C语言读取配置文件
自从大学学完C之后,就再也没用过它了,
在网上找代码,七拼八凑之后,终于成形~~勉强能用,不喜勿喷,^_^!
int GetValue(const wchar_t *key, wchar_t *value) { FILE* fpcfg = NULL; wchar_t var[256], val[256];//key,value wchar_t linebuf[1024]; wchar_t* ptr1 = NULL; wchar_t* ptr2 = NULL; wchar_t* delimiter = NULL; int k = 0; assert(key != NULL && value != NULL); //testConfig.ini中的内容为: //key1 = value1 //key2 = value2 fpcfg = fopen("testConfig.ini", "rt"); if(fpcfg == NULL) { return -1; } while(fgetws(linebuf, sizeof(linebuf), fpcfg) != NULL) { //ignore annotation line if(linebuf[0]=='#' || linebuf[0]==';') { continue; } //ignore empty line ptr1 = linebuf; while(*ptr1==0x20 || *ptr1=='\t') ptr1++; if(!*ptr1 || *ptr1=='\n') { continue; } //search "=" ptr2 = ptr1; while(*ptr2 && *ptr2!='=') { ptr2++; } delimiter = *ptr2?ptr2:NULL; //if current line start with "=", continue next line if(!delimiter || delimiter==ptr1) { continue; } //*delimiter = '\0'; ptr2 = delimiter-1; //ignore blank before "=" while(*ptr2==0x20 || *ptr2=='\t') { ptr2--;} //check key length k = ptr2-ptr1+1; if(k>(int)sizeof(var)-1) { //The key name is out of length." continue; } //save key name ptr2 = var; while(k--) { *ptr2++ = *ptr1++; } *ptr2 = '\0'; //locate value's start point(may be '\0') ptr1 = delimiter+1; //ignore blank after "=" while(*ptr1==0x20 || *ptr1=='\t') { ptr1++; } //set ptr2 point to line end ptr2 = linebuf; while(*ptr2) {ptr2++;} ptr2--; if(*ptr2=='\n') { *ptr2-- = '\0'; } //ignore blank line end //if value is empty,ptr2 --> = , ptr1>ptr2 while(*ptr2==0x20 || *ptr2=='\t' ) { ptr2--; } //check value length k = ptr2-ptr1+1; if(k>(int)sizeof(val)-1) { //The value is out of length" continue; } //save value ptr2 = val; while(k-->0) { *ptr2++ = *ptr1++; } *ptr2 = '\0'; if(wcsncmp(var,key, wcslen(var) > wcslen(key) ? wcslen(var) : wcslen(key))==0){ wcsncpy(value,val, wcslen(val)); return 0; } } fclose(fpcfg); fpcfg = NULL; return -1; }
恩,再来个main方法测试下:
int _tmain(int argc, wchar_t* argv[]) { wchar_t value[256] = {0}; wchar_t keyParam[256] = L"ip"; wchar_t *temp = (wchar_t *)malloc(sizeof(wchar_t) * 256); if(temp != NULL){ memset(temp, 0x00, sizeof(wchar_t) * 256); }else{ return -1; } if(0 == GetValue(keyParam, temp)){ wcsncpy(value, temp, wcslen(temp)); wprintf(L"Found: %s\n", value); }else{ wprintf(L"Not Found!!\n"); } if(temp != NULL) { free(temp); temp = NULL; } return 0; }
好吧,这确实是个很丑陋的版本,仅供自己留着备用。
点这里下载