Open In App

How to Read a File Line by Line in C?

Last Updated : 29 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C, reading a file line by line is a process that involves opening the file, reading its contents line by line until the end of the file is reached, processing each line as needed, and then closing the file.

Reading a File Line by Line in C

Reading a file line by line is a step by step:

1. Opening the File: The first step in the process of reading a file line by line is to open the file. Which is done using the fopen() function.

C
fopen(filename, mode);

where,

  • filename: pointer to string defining the path of the file which is to be opened. Ex: "/home/user/documents/example.txt";
  • mode:  pointer to string specifying the mode in which the file is to be opened. The value of mode string is different for different modes. Example:
    • "r" - to open a file in read only mode.
    • "w" - to open a file in writing mode. In this mode the contents of the file are overwritten If the file exists. else a new file is created.

2. Reading Each Line of the File: To read lines of the file, we can use fgets() function which is a standard way to read a file line by line. It reads a string from the specified file until a newline character is encountered, or the end-of-file is reached.

C
fgets(str, num, stream);

where,

  • char *str: pointer to the buffer where the read line will be stored.
  • num: maximum number of characters to read (including NULL character).
  • stream: pointer to the FILE structure representing the opened file.

3. Closing the file: Finally, we close the file using close() function.

C
fclose(stream);

where,

  • stream: Pointer to the FILE structure representing the opened file.

Implementation

The below program demonstrates how we can read a file line by line using fgets() function in C.

C
#include <stdio.h>
#include <stdlib.h>

int main()
{
    // Create a file pointer and open the file "GFG.txt" in
    // read mode.
    FILE* file = fopen("GFG.txt", "r");

    // Buffer to store each line of the file.
    char line[256];

    // Check if the file was opened successfully.
    if (file != NULL) {
        // Read each line from the file and store it in the
        // 'line' buffer.
        while (fgets(line, sizeof(line), file)) {
            // Print each line to the standard output.
            printf("%s", line);
        }

        // Close the file stream once all lines have been
        // read.
        fclose(file);
    }
    else {
        // Print an error message to the standard error
        // stream if the file cannot be opened.
        fprintf(stderr, "Unable to open file!\n");
    }

    return 0;
}

Input File: GFG.txt

fileInputC
GFG.txt

Output

FileOutputC
Output

Next Article

Similar Reads