C programming language provides the ability to read a file line by line. A file may contain multiple lines to store content. There are different ways to get this content where reading line by line is a method. The C programming language provides different methods to read a file line by line. In this tutorial, we examine the most practical and easy-to-implement methods to read a file line by line.
Read File Line By Line with getline() Method
The getline()
method is provided by the <stdio.h>
library which means we should include this library to use getline() method. Simply the getline() method reads the entire line from the stream where it is a file for our case. The getline() reads until it reaches the new line control character. In the following example, we read the file named “db.txt” line by line. The while
loop used to iterate over the line by jumping new line after line read.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/home/ismail/db.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
After the line-by-line read operation is completed we should close the file to release resources with the fclose() method.