J
Jeff Rodriguez
There has GOT to be a standard way to this. I'm sure I'm not the only
person who would want to have a function that gets one line from a file
pointer with a dynamic length. Here's what I have right now:
( also at http://gurugeek.com/jeff/programming/wordjumble/wordjumble.c )
void get_line( FILE *fp, char **line )
{
int ch;
int iteration = 0;
char *tmp = NULL;
/* {{{ Code Fold: Loop until we reach EOF or a newline */
while ( (ch = fgetc(fp)) != '\n' && !feof(fp))
{
/* {{{ Code Fold: (Re)allocate Memory */
if ((tmp = realloc((*line), (iteration + 2) * sizeof(char))) ==
NULL )
{
puts("Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
else
{
*line = tmp;
}
/* }}} Code Fold: (Re)allocate Memory */
(*line)[ iteration ] = (char)ch;
iteration++;
}
/* }}} Code Fold: Loop until we reach EOF or a newline */
}
Also, my main function:
int main( int argc, char *argv[] )
{
unsigned int count = 0;
while ( !feof(stdin) )
{
char *line = NULL;
count++;
printf("> ");
get_line(stdin, &line);
printf("%s\n", line);
// Don't forget to
free(line);
}
printf("\nTotal lines: %u\n", count);
return EXIT_SUCCESS;
}
Together they seem to give some unexpected output:
jeff@andromeda% gcc wordjumble.c
jeff@andromeda% ./a.out
I'm freeing 'line' so that's the problem?
person who would want to have a function that gets one line from a file
pointer with a dynamic length. Here's what I have right now:
( also at http://gurugeek.com/jeff/programming/wordjumble/wordjumble.c )
void get_line( FILE *fp, char **line )
{
int ch;
int iteration = 0;
char *tmp = NULL;
/* {{{ Code Fold: Loop until we reach EOF or a newline */
while ( (ch = fgetc(fp)) != '\n' && !feof(fp))
{
/* {{{ Code Fold: (Re)allocate Memory */
if ((tmp = realloc((*line), (iteration + 2) * sizeof(char))) ==
NULL )
{
puts("Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
else
{
*line = tmp;
}
/* }}} Code Fold: (Re)allocate Memory */
(*line)[ iteration ] = (char)ch;
iteration++;
}
/* }}} Code Fold: Loop until we reach EOF or a newline */
}
Also, my main function:
int main( int argc, char *argv[] )
{
unsigned int count = 0;
while ( !feof(stdin) )
{
char *line = NULL;
count++;
printf("> ");
get_line(stdin, &line);
printf("%s\n", line);
// Don't forget to
free(line);
}
printf("\nTotal lines: %u\n", count);
return EXIT_SUCCESS;
}
Together they seem to give some unexpected output:
jeff@andromeda% gcc wordjumble.c
jeff@andromeda% ./a.out
long string long string
short shortstring
I'm freeing 'line' so that's the problem?