Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file with variable line lengths line by line in c

Tags:

c

file-io

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!

like image 276
cskwrd Avatar asked Jun 21 '10 18:06

cskwrd


People also ask

How read a file line by line in C?

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.

Does Fscanf read line by line?

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.

Does fgets read line by line?

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.

What is read line in C?

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 );


2 Answers

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;
}
like image 178
R Samuel Klatchko Avatar answered Oct 27 '22 22:10

R Samuel Klatchko


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.)

like image 33
u0b34a0f6ae Avatar answered Oct 28 '22 00:10

u0b34a0f6ae