简单配置文件的读取以及保存。
#define LINE_BUF_SIZE 128 char read_upgrade_version(char *file_path,const char *type, char *value) { char line[LINE_BUF_SIZE] = {0}; FILE *fp = NULL; char *pType = NULL; fp = fopen(file_path, "r"); if (!fp) { printf("Can't open %s",file_path); return -1; } while (!feof(fp)) { if(fgets(line, LINE_BUF_SIZE, fp) == NULL) { break; } pType = strstr(line, "="); if(pType == NULL) { continue; } pType = strstr(line, type); if (pType) { pType ++; pType += strlen(type); if (pType) { strcpy(value, pType); break; } } } fclose(fp); return 0; }
#define LINE_NUM 12 int save_upgrade_version(char *file_path,const char *type, char *value) { int i; char flag = 0,cnt = 0; struct info_t info[LINE_NUM]; char linebuffer[LINE_BUF_SIZE] = {0}; char buffer[LINE_BUF_SIZE * 2]; char *pType = NULL; FILE *fp = fopen(file_path, "r"); if(fp == NULL) { printf("open error"); return 1; } for(i = 0 ; i < LINE_NUM ; i++) { char *ret = fgets(linebuffer, sizeof(linebuffer), fp); if(ret == NULL) { break; } pType = strstr(linebuffer, "="); if(pType == NULL) { continue; } memcpy(info[i].type, linebuffer, pType - linebuffer); info[i].type[pType - linebuffer] ='\0'; strcpy(info[i].value, pType + 1); if(!strcmp(info[i].type, type)) { strcpy(info[i].value,value); info[i].value[strlen(value)] = '\n'; info[i].value[strlen(value) + 1] = '\0'; flag = 1; } memset(linebuffer,0,sizeof(linebuffer)); cnt++; } fclose(fp); fp = fopen(file_path,"w"); if(fp == NULL) { return 1; } if(flag == 0) { strcpy(info[cnt].type,type); strcpy(info[cnt].value,value); info[i].value[strlen(value)] = '\n'; info[i].value[strlen(value) + 1] = '\0'; cnt++; } for(i = 0 ; i < cnt ; i++) { memset(buffer,0,sizeof(buffer)); sprintf(buffer,"%s=%s",info[i].type,info[i].value); fprintf(fp,"%s",buffer); } fclose(fp); return 0; }
目前配置文件内容使用“=”号分割。保存时采用的是读取整个文件内容,修改对应行后再保存,可以保存没有存在的字段。如果有很多行的话这个就不适用了。
这个代码只适用与小量的配置保存与更改需要。
Go as far as your heart will take you.