C/read file into char*

From Attie's Wiki
Jump to: navigation, search

This could be considerably improved by using fseek() and ftell(). However that approach won't work with streams, only static files.

#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 (!filename || !data) return 3;
 
	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;
}
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox