Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #58 Extract file content to a string

Create the string lines from the content of the file with filename f.

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));

while(!feof(file))
{
	assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
	len+=fread(lines,1,0x1000,file);
}

assert(lines=realloc(lines,len*sizeof(char)));

New implementation...
< >
programming-idioms.org