project/weight.c
/**
 * Stores all current users and corresponding logs as JSON.
 */
Stores all current users and corresponding logs as JSON.
Stores all current users and corresponding logs as JSON .
void saveToJson()
{
  int i, j;
  cJSON * root = cJSON_CreateArray();
  for (i = 0; i < MAX_USERS; i++)
  {
    if (users[i].name)
    {
      cJSON * user;
      struct profile prof = users[i];
      cJSON_AddItemToArray(root, user = cJSON_CreateObject());
      cJSON_AddNumberToObject(user, "id", prof.id);
      cJSON_AddStringToObject(user, "name", prof.name);
      cJSON_AddNumberToObject(user, "height", prof.height);
      cJSON_AddNumberToObject(user, "age", prof.age);
      cJSON_AddStringToObject(user, "gender", prof.gender);
      cJSON * logs = cJSON_CreateArray();
      for (j = 0; j < prof.numLogs; j++)
      {
        cJSON * log;
        struct log lg = prof.logs[j];
        cJSON_AddItemToArray(logs, log = cJSON_CreateObject());
        cJSON_AddNumberToObject(log, "id", lg.id);
        cJSON_AddNumberToObject(log, "weight", lg.weight);
        cJSON_AddStringToObject(log, "time", lg.time);
      }
      cJSON_AddItemToObject(user, "logs", logs);
    }
  }
  char * rendered = cJSON_Print(root);
  FILE *fp = fopen(F_JSON, "w");
  int res = fputs(rendered, fp);
  if (res == EOF)
  {
    fprintf(stderr, "Unable to save: %s\n", strerror(errno));
  } else {
    printf("Success saving %s\n", F_JSON);
  }
  fclose(fp);
}
void saveToJson ( ) { int i , j ; cJSON * root = cJSON_CreateArray ( ) ; for ( i = 0 ; i < MAX_USERS ; i ++ ) { if ( users [ i ] . name ) { cJSON * user ; struct profile prof = users [ i ] ; cJSON_AddItemToArray ( root , user = cJSON_CreateObject ( ) ) ; cJSON_AddNumberToObject ( user , " " , prof . id ) ; cJSON_AddStringToObject ( user , " " , prof . name ) ; cJSON_AddNumberToObject ( user , " " , prof . height ) ; cJSON_AddNumberToObject ( user , " " , prof . age ) ; cJSON_AddStringToObject ( user , " " , prof . gender ) ; cJSON * logs = cJSON_CreateArray ( ) ; for ( j = 0 ; j < prof . numLogs ; j ++ ) { cJSON * log ; struct log lg = prof . logs [ j ] ; cJSON_AddItemToArray ( logs , log = cJSON_CreateObject ( ) ) ; cJSON_AddNumberToObject ( log , " " , lg . id ) ; cJSON_AddNumberToObject ( log , " " , lg . weight ) ; cJSON_AddStringToObject ( log , " " , lg . time ) ; } cJSON_AddItemToObject ( user , " " , logs ) ; } } char * rendered = cJSON_Print ( root ) ; FILE * fp = fopen ( F_JSON , " " ) ; int res = fputs ( rendered , fp ) ; if ( res == EOF ) { fprintf ( stderr , " \n " , strerror ( errno ) ) ; } else { printf ( " \n " , F_JSON ) ; } fclose ( fp ) ; }
Stores all current users and corresponding logs as JSON.
Stores all current users and corresponding logs as JSON .
//printf("-----saveToJson()-----\n");