In C, is there a way to read a text file line by line without knowing how much space to allocate for it?
here's an example of what I mean:
fgets(line, <dynamic line size>, fileHandle);
Thanks for the help!
The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be. You can find all the code examples and the input file at the GitHub repo for this article.
The fscanf reads until it meats \n (new line) character ,whereas you can use fgets to read all lines with the exact same code you used! Hope that helped :) Save this answer.
The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first.
The function readline () prints a prompt and then reads and returns a single line of text from the user. The line readline returns is allocated with malloc () ; you should free () the line when you are done with it. The declaration for readline in ANSI C is. char *readline (char * prompt );
Nothing automatic. You need to keep growing your buffer and calling fgets until you get the newline or the EOF.
// NOTE: not production ready as does not handle memory allocation failures
size_t alloced = 128;
char *p = malloc(alloced);
char *walk = p;
size_t to_read = alloced;
for (;;) {
if (fgets(walk, to_read, fp) == NULL)
break;
if (walk[strlen(walk) - 1] == '\n')
break;
to_read = alloced;
alloced *= 2;
p = realloc(p, allocated);
walk = p + to_read;
}
If you have glibc or another libc that supports POSIX (2008), you can use getline
:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.
If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (The value in *n is ignored.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With