Skip to content

Instantly share code, notes, and snippets.

@tymbark
Created August 13, 2018 13:37
Show Gist options
  • Save tymbark/5c16a30ff89c524b273ec8f451e6c453 to your computer and use it in GitHub Desktop.
Save tymbark/5c16a30ff89c524b273ec8f451e6c453 to your computer and use it in GitHub Desktop.
char* read_file(const char* filepath) {
FILE *fp = fopen(filepath, "r");
if (fp == NULL) {
perror("");
return NULL;
}
if (fseek(fp, 0, SEEK_END) != 0) {
perror("");
return NULL;
}
int bufsize = ftell(fp);
if (bufsize < 1) {
perror("");
return NULL;
}
errno = 0;
rewind(fp);
if (errno != 0) {
perror("");
return NULL;
}
char *buf = malloc(sizeof(char) * (bufsize));
if (buf == NULL) {
perror("");
return NULL;
}
memset(buf, '\0', sizeof(char) * (bufsize));
char str[200];
while (fgets(str, 200, fp) != NULL) {
if (sprintf(buf + strlen(buf), "%s", str) < 0) {
perror("");
return NULL;
}
}
dlog_print(DLOG_DEBUG, LOG_TAG, "read_file 1 %s ", buf);
if (fclose(fp) != 0) {
dlog_print(DLOG_ERROR, LOG_TAG, "fclose error: %s", strerror(errno));
return NULL;
}
dlog_print(DLOG_DEBUG, LOG_TAG, "read_file 2");
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment