Skip to content

Instantly share code, notes, and snippets.

@cpq
Last active November 5, 2019 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpq/380419e2460e19617f345147e9386936 to your computer and use it in GitHub Desktop.
Save cpq/380419e2460e19617f345147e9386936 to your computer and use it in GitHub Desktop.
char *read_file(const char *path) {
FILE *fp;
char *data = NULL;
if ((fp = fopen(path, "rb")) == NULL) {
} else if (fseek(fp, 0, SEEK_END) != 0) {
fclose(fp);
} else {
size_t size = ftell(fp);
data = (char *) malloc(size + 1);
if (data != NULL) {
fseek(fp, 0, SEEK_SET); /* Some platforms might not have rewind(), Oo */
if (fread(data, 1, size, fp) != size) {
free(data);
return NULL;
}
data[size] = '\0';
}
fclose(fp);
}
return data;
}
struct config { a, b int; };
char read_json(struct config *c) {
double dv;
char *buf = read_file("state.json");
int len = buf == NULL ? 0 : strlen(buf);
if (mjson_get_number(buf, len, "$.a", &dv)) c->a = dv;
if (mjson_get_number(buf, len, "$.b", &dv)) c->b = dv;
free(buf);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment