public
Last active

read string from file, dynamically allocating memory

  • Download Gist
dynastr.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <stdlib.h>
#include <stdio.h>
 
char * read_line( FILE * f ) {
int cap = 32, next = 0, c;
char * p = malloc( cap );
while( 1 ) {
if ( next == cap ) {
p = realloc( p, cap *= 2 );
}
c = fgetc( f );
if ( c == EOF || c == '\n' ) {
p[next++] = 0;
break;
}
p[next++] = c;
}
if ( c == EOF && next == 1 ) {
free( p );
p = NULL;
}
 
return p;
}
int main() {
char * s;
while( s = read_line( stdin ) ) {
printf( "%s\n", s );
free( s );
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.