Skip to content
Create a gist now

Instantly share code, notes, and snippets.

read string from file, dynamically allocating memory
#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 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.