工作需要,网上找了一点代码,以此为基础做了修改。写的部分还没做,以后有机会再发布。
从方便来看,最好是实现一个字典,把值放进字典中,访问起来特别方便。
/** 允许section为空,此时搜索文件的全部。 */ int gh_conf_read_value(const char* psFile, const char* psSection, const char* psKey, char* psValue) { FILE* pFile = NULL; char lineContent[LINE_CONTENT_MAX_LEN]; BOOL bFoundSection = BOOL_FALSE; BOOL bFoundKey = BOOL_FALSE; char cHead = 0; int nLength = 0; char *pHead = NULL; if (psKey == NULL || psFile == NULL || psValue == NULL) { return -1; } pFile = fopen(psFile, "r"); if (pFile == NULL) { GH_LOG_INFO("%s: Opent file %s failed.\n", __FILE__, psFile); return -1; } //找到sestion if (psSection != NULL) { while (feof(pFile) == 0) { memset(lineContent, 0, LINE_CONTENT_MAX_LEN); fgets(lineContent, LINE_CONTENT_MAX_LEN, pFile); cHead = lineContent[0]; //去空格 if ((cHead == '#') || (cHead == '\0') || (cHead == '\r') || (cHead == '\n')) { continue; } //合法的section, 自动认为 lineContent[nLength-1-1] == ']' if (cHead == '[') { //[]之外,还有个\n nLength = strlen(lineContent)-3; if (!strncmp(lineContent+1, psSection, nLength)) { bFoundSection = BOOL_TRUE; break; } continue; } } //没找到,直接返回吧。 if (!bFoundSection) { fclose(pFile); return -1; } } //找KEY while (feof(pFile) == 0) { memset(lineContent, 0, LINE_CONTENT_MAX_LEN); fgets(lineContent, LINE_CONTENT_MAX_LEN, pFile); cHead = lineContent[0]; if ((cHead == '#') || (cHead == '\0') || (cHead == '\r') || (cHead == '\n')) { continue; } //碰到新的节,要说明没找到。 if (psSection != NULL && cHead == '[') { break; } //check key if (strncmp(lineContent, psKey, strlen(psKey)) == 0) { bFoundKey = BOOL_TRUE; break; } } //先关闭,后面省事。 fclose(pFile); pFile = NULL; //没找到,直接返回吧。 if (!bFoundKey) { return -1; } //切分值。从第一个等号开始,后面全部是值。 pHead = strchr(lineContent, '='); if (pHead == NULL) { return -1; } //跳过= pHead++; nLength = strlen(pHead)-1; //最后一个是回车 if (pHead[nLength] == '\n') { pHead[nLength] = 0; } strcpy(psValue, pHead); return 0; }