Skip to content

Instantly share code, notes, and snippets.

@neilbutterworth
Created December 19, 2012 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilbutterworth/4337666 to your computer and use it in GitHub Desktop.
Save neilbutterworth/4337666 to your computer and use it in GitHub Desktop.
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