Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

read string from file, dynamically allocating memory

View dynastr.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 33
#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.