配置文件内容:
[cfg] ip=192.168.10.1 port=5890
方式一:纯粹的读匹配
static void test_get_cfg_value(char *file_path) { char ip[110] = { 0 }; char port[110] = { 0 }; int len = 0; int i = 0; int j = 0; char line[1024] = { 0 }; FILE *fp = fopen(file_path, "r"); if (!fp) { return; } while (fgets(line, sizeof(line), fp) != NULL) { if ('i' == line[0]) { i = 0; j = 0; len = strlen(line); while (i<len) { i++; if ('=' == line[i]) { break; } } // 去掉空格 while (line[i+1] == ' ') { i++; } // 提取值 while (i++) { if ('\n' == line[i]) break; ip[j] = line[i]; j++; } printf("aaaa:%s\n", ip); } if ('p' == line[0]) { i = 0; j = 0; len = strlen(line); while (i<len) { i++; if ('=' == line[i]) { break; } } // 去掉空格 while (line[i + 1] == ' ') { i++; } // 提取值 while (i++) { if ('\n' == line[i]) break; port[j] = line[i]; j++; } printf("aaaa:%s\n", port); } } }
方式二:调用库函数
static void read_cfg_value(char file_path[], char *key, char *val, int key_len) { char *filePath = file_path; FILE *fptr; char str[1024]; char pro[512], after[512]; char *p; if ((fptr = fopen(file_path, "rb+")) == NULL) { printf("open fialed!, file path:%s, error:%s\n", file_path, strerror(errno)); return NULL; } while (!feof(fptr)) { memset(pro, 0, sizeof(pro)); memset(after, 0, sizeof(after)); memset(str, 0, sizeof(str)); fgets(str, sizeof(str), fptr); if ((p = strchr(str, '=')) == NULL) continue; memcpy(pro, str, p - str); memcpy(after, p + 1, strlen(str) - (p - str)); if (pro && strncmp(pro, key, key_len)) continue; memcpy(val, after, strlen(after)); fclose(fptr); fptr = NULL; return val; } fclose(fptr); fptr = NULL; return NULL; } // 将字符串转换为整数 static int convert_value_to_int(char *str) { if (NULL != str) return atoi(str); else return 0; }
主函数:
int main() { char filePath[] = "./ice.conf"; // 方式一 test_get_cfg_value(filePath); char ip[64] = { 0 }; char tmp[64] = { 0 }; int port = 0; // 方式二 read_cfg_value(filePath, "ip", ip, sizeof("ip")); read_cfg_value(filePath, "port", tmp, sizeof("port")); port = convert_value_to_int(tmp); printf("ip:%s\nport:%d\n", ip, port); system("pause"); return 0; }运行结果:
可能会出现的问题:
Run-Time Check Failure #2 - Stack around the variable 'xxx';
大多数情况下是由于memcpy函数使用的时候,第三个参数的问题,导致栈溢出。
