Read a File Line by Line in C

To read a file line by line in C, you can use functions like fgets() or getline() which allow you to process each line sequentially from a file, making it easier to handle text data.


Example 1: Reading a File Using fgets()

In this example, we will read a file named example.txt line by line using the fgets() function. This method reads a fixed-size string from the file and is ideal when you know the maximum line length.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Open the file in read mode
    FILE *fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }
    
    char buffer[256]; // Buffer to store each line

    // Read each line using fgets until end of file is reached
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer);
    }

    // Close the file
    fclose(fp);
    return 0;
}

Explanation:

  1. The file example.txt is opened in read mode using fopen(), and a file pointer fp is obtained.
  2. A buffer array buffer[256] is declared to store each line read from the file.
  3. The while loop uses fgets() to read up to 255 characters (plus the null terminator) from the file into buffer. It continues until the end-of-file is reached (i.e., fgets() returns NULL).
  4. Inside the loop, printf() outputs the content of buffer, effectively printing each line.
  5. After processing all lines, the file is closed using fclose() to free up resources.

Output:

Hello, World!
This is an example file.
It contains multiple lines of text.

Example 2: Reading a File Using getline()

In this example, we will use the getline() function (a POSIX extension) to read a file named example.txt line by line. This function dynamically allocates memory for the line, making it useful when line lengths are unpredictable.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    // Open the file in read mode
    FILE *fp = fopen("example.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    char *line = NULL;   // Pointer to hold the address of the line buffer
    size_t len = 0;      // Variable to store the size of the buffer
    ssize_t read;        // Variable to store the number of characters read

    // Read each line using getline until end of file is reached
    while ((read = getline(&line, &len, fp)) != -1) {
        printf("%s", line);
    }

    // Free the memory allocated by getline and close the file
    free(line);
    fclose(fp);
    return 0;
}

Explanation:

  1. The file example.txt is opened in read mode with fopen(), and fp is used as the file pointer.
  2. A pointer line is initialized to NULL and len is set to 0. These are used by getline() to allocate a buffer dynamically.
  3. The while loop calls getline(), which reads an entire line from the file into the buffer pointed to by line, updating len as needed. The loop continues until getline() returns -1 (end-of-file).
  4. Inside the loop, printf() prints the line read from the file.
  5. After reading all lines, the dynamically allocated memory for line is freed using free(), and the file is closed using fclose().

Output:

Hello, World!
This is an example file.
It contains multiple lines of text.

Conclusion

In this tutorial, we explored two methods to read a file line by line in C:

  1. Using fgets(): Reads a fixed-size buffer from the file, making it suitable when the maximum line length is known.
  2. Using getline(): Dynamically allocates memory for each line, which is useful for files with unpredictable line lengths.