N
Noob
Hello group,
Here's my attempt at writing a "get_line" implementation, which
reads an entire line from a file stream, dynamically allocating
the space needed to store said line.
Since this is for my own personal use, I didn't bother handling
out-of-memory conditions elegantly. I just kick the bucket.
("We all kick the bucket in the end, in the end.")
EOF is signaled by returning NULL.
I'd like to hear suggestions/criticism.
#include <stdio.h>
#include <stdlib.h>
#define BUFLEN 4000
char *get_line(FILE *stream)
{
char *s = NULL; size_t len = 0; int c;
do c = fgetc(stream); while (c == '\n'); /* ignore leading empty lines */
if (c == EOF) return NULL;
ungetc(c, stream);
while ( 1 )
{
size_t max = len + BUFLEN;
s = realloc(s, max);
if (s == NULL) exit(EXIT_FAILURE);
while (len < max)
{
c = fgetc(stream);
if (c == EOF || c == '\n')
{
s[len] = '\0';
return realloc(s, len+1);
}
s[len++] = c;
}
}
}
Regards.
Here's my attempt at writing a "get_line" implementation, which
reads an entire line from a file stream, dynamically allocating
the space needed to store said line.
Since this is for my own personal use, I didn't bother handling
out-of-memory conditions elegantly. I just kick the bucket.
("We all kick the bucket in the end, in the end.")
EOF is signaled by returning NULL.
I'd like to hear suggestions/criticism.
#include <stdio.h>
#include <stdlib.h>
#define BUFLEN 4000
char *get_line(FILE *stream)
{
char *s = NULL; size_t len = 0; int c;
do c = fgetc(stream); while (c == '\n'); /* ignore leading empty lines */
if (c == EOF) return NULL;
ungetc(c, stream);
while ( 1 )
{
size_t max = len + BUFLEN;
s = realloc(s, max);
if (s == NULL) exit(EXIT_FAILURE);
while (len < max)
{
c = fgetc(stream);
if (c == EOF || c == '\n')
{
s[len] = '\0';
return realloc(s, len+1);
}
s[len++] = c;
}
}
}
Regards.