C/read file into char*
From Attie's Wiki
(Difference between revisions)
(Created page with "<source lang="c"> #define CHUNK_SIZE 128 int readFile(char *filename, char **data) { FILE *f; char *c; /* contents*/ void *p; int l; - →length: int r; /* amoun...") |
m |
||
Line 2: | Line 2: | ||
#define CHUNK_SIZE 128 | #define CHUNK_SIZE 128 | ||
int readFile(char *filename, char **data) { | int readFile(char *filename, char **data) { | ||
− | + | FILE *f; | |
− | + | ||
− | + | char *c; /* contents*/ | |
− | + | void *p; | |
− | + | ||
− | + | int l; /* length */ | |
− | + | int r; /* amount read */ | |
− | + | int s; /* memory size */ | |
− | + | ||
− | + | if ((f = fopen(filename,"r")) == NULL) { | |
− | + | perror("fopen()"); | |
return 1; | return 1; | ||
− | + | } | |
− | + | ||
− | + | c = NULL; | |
− | + | l = 0; | |
− | + | s = 0; | |
− | + | while (!feof(f)) { | |
− | + | s += CHUNK_SIZE; | |
− | + | if ((p = realloc(c, sizeof(char) * s)) == NULL) { | |
− | + | perror("realloc()"); | |
− | + | goto die; | |
− | + | } | |
− | + | c = p; | |
− | + | r = fread(&(c[l]), 1, s - l, f); | |
− | + | if (!r) { | |
− | + | if (feof(f)) break; | |
− | + | /* else error */ | |
− | + | fprintf(stderr,"fread(): An error occured\n"); | |
− | + | goto die; | |
− | + | } else if (r < 0) { | |
− | + | perror("fread()"); | |
− | + | break; | |
− | + | } | |
− | + | l += r; | |
− | + | } | |
− | + | ||
− | + | if ((p = realloc(c, sizeof(char) * (l + 1))) == NULL) { | |
− | + | perror("realloc()"); | |
− | + | } else { | |
− | + | c = p; | |
− | + | } | |
− | + | ||
− | + | c[l] = '\0'; | |
− | + | ||
fclose(f); | fclose(f); | ||
− | + | ||
*data = c; | *data = c; | ||
return 0; | return 0; | ||
+ | |||
die: | die: | ||
fclose(f); | fclose(f); |
Revision as of 12:19, 8 September 2012
#define CHUNK_SIZE 128 int readFile(char *filename, char **data) { FILE *f; char *c; /* contents*/ void *p; int l; /* length */ int r; /* amount read */ int s; /* memory size */ if ((f = fopen(filename,"r")) == NULL) { perror("fopen()"); return 1; } c = NULL; l = 0; s = 0; while (!feof(f)) { s += CHUNK_SIZE; if ((p = realloc(c, sizeof(char) * s)) == NULL) { perror("realloc()"); goto die; } c = p; r = fread(&(c[l]), 1, s - l, f); if (!r) { if (feof(f)) break; /* else error */ fprintf(stderr,"fread(): An error occured\n"); goto die; } else if (r < 0) { perror("fread()"); break; } l += r; } if ((p = realloc(c, sizeof(char) * (l + 1))) == NULL) { perror("realloc()"); } else { c = p; } c[l] = '\0'; fclose(f); *data = c; return 0; die: fclose(f); if (c) free(c); return 2; }