He escrito un programa para sondear los límites de las funciones C time.h de un sistema y las descargo en JSON. Luego, otras cosas que dependen de esas funciones pueden conocer sus límites.¿Hay alguna manera de volcar una C struct?
# system time.h limits, as JSON
{
"gmtime": { "max": 2147483647, "min": -2147483648 },
"localtime": { "max": 2147483647, "min": -2147483648 },
"mktime": {
"max": { "tm_sec": 7, "tm_min": 14, "tm_hour": 19, "tm_mday": 18, "tm_mon": 0, "tm_year": 138, "tm_wday": 1, "tm_yday": 17, "tm_isdst": 0 },
"min": { "tm_sec": 52, "tm_min": 45, "tm_hour": 12, "tm_mday": 13, "tm_mon": 11, "tm_year": 1, "tm_wday": 5, "tm_yday": 346, "tm_isdst": 0 }
}
}
gmtime() y localtime() son bastante simple, que acaba de tomar los números, pero mktime() toma una estructura tm. Escribí una función personalizada para convertir una estructura tm en un hash JSON.
/* Dump a tm struct as a json fragment */
char * tm_as_json(const struct tm* date) {
char *date_json = malloc(sizeof(char) * 512);
#ifdef HAS_TM_TM_ZONE
char zone_json[32];
#endif
#ifdef HAS_TM_TM_GMTOFF
char gmtoff_json[32];
#endif
sprintf(date_json,
"\"tm_sec\": %d, \"tm_min\": %d, \"tm_hour\": %d, \"tm_mday\": %d, \"tm_mon\": %d, \"tm_year\": %d, \"tm_wday\": %d, \"tm_yday\": %d, \"tm_isdst\": %d",
date->tm_sec, date->tm_min, date->tm_hour, date->tm_mday,
date->tm_mon, date->tm_year, date->tm_wday, date->tm_yday, date->tm_isdst
);
#ifdef HAS_TM_TM_ZONE
sprintf(&zone_json, ", \"tm_zone\": %s", date->tm_zone);
strcat(date_json, zone_json);
#endif
#ifdef HAS_TM_TM_GMTOFF
sprintf(&gmtoff_json", \"tm_gmtoff\": %ld", date->tm_gmtoff);
strcat(date_json, gmtoff_json);
#endif
return date_json;
}
¿Hay alguna manera de hacer esto genéricamente, para cualquier estructura dada?
Nota: C, no C++.
1 para mí superando a la misma. –