#include "smartlight.h" #include "cJSON.h" cJSON *dofile(char *filename) { FILE *f; long len; char *data; cJSON *json,*ret; f=fopen(filename,"rb"); fseek(f,SEEK_END); len=ftell(f); fseek(f,SEEK_SET); data=(char*)malloc(len+1); fread(data,1,len,f); data[len]='\0'; json=cJSON_Parse(data); if (!json) { printf("Error before: [%s]\n",cJSON_GetErrorPtr()); ret = NULL; goto EXIT; } else { //printf("%s\n",data); ret = json; } EXIT: free(data); fclose(f); return ret; } int write_file(char *filename,char *out) { FILE *fp = NULL; fp = fopen(filename,"a+"); if(fp == NULL) { fprintf(stderr,"open file Failed\n"); exit(-1); } fprintf(fp,"%s",out); if(fp != NULL) fclose(fp); } int main() { cJSON *root,*basicpara; char *out; root = dofile("basicparameter.cfg"); out = cJSON_Print(root); printf("before modify:%s\n",out); free(out); basicpara = cJSON_GetObjectItem(root,"basicparameter"); cJSON_GetObjectItem(basicpara,"mode")->valueint = 0; //cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0; cJSON_GetObjectItem(basicpara,"TimeoutPoweron")->valueint = 10; //cJSON_GetObjectItem(basicpara,"TimeoutPoweron")->valuedouble = 10; out = cJSON_Print(root); printf("after modify:%s\n",out); free(out); //write_file("basicparameter.cfg",out); cJSON_Delete(root); return 0; }
刚开始只修改了valueint的值,结果显示修改前后的结果一样。@H_404_1@
cJSON_GetObjectItem(basicpara,"mode")->valueint = 0;
@H_404_1@
然后修改valuedouble的值,才能真能修改json文件。@H_404_1@
@H_404_1@
cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0;也只是修改了valuedouble的值。
所以如果想要修改valueint的值必须同时调用@H_404_1@
cJSON_GetObjectItem(basicpara,"mode")->valueint = 0; cJSON_GetObjectItem(basicpara,"mode")->valuedouble = 0;引用链接: https://sourceforge.net/p/cjson/discussion/998970/thread/5c13b93f/