In this article, we are going to learn How to Read File Line by Line in C language.We will read each line from the text file in each iteration.
C fscanf function
The fscanf function is available in the C library. This function is used to read formatted input from a stream. The syntax of fscanf function is:
int fscanf(FILE *stream, const char *format, …)
Parameters
- stream − This is the pointer to a FILE object that identifies the stream.
- format − This is the C string that contains one or more of the following items − Whitespace character, Non-whitespace character, and Format specifiers. A format specifier will be as [=%[*][width][modifiers]type=].
1. How to Read File Line by Line in C
Here we are making use of the fscanf function to read the text file.The first thing we are going to do is open the file in reading mode. So using fopen() function and “r” read mode we opened the file.The next step is to find the file stats like what is the size of the data this file contains. so we can allocate exact memory for the buffer that is going to hold the content of this file. We are using the stat() function to find the file size.
- Once we have the size and buffer allocated for this size, we start reading the file by using the fscanf() function.
- We keep reading the file line by line until we reach the end of the file. In fscanf function, we are passing \n as the argument so we can read the text until we find a next line character.
- The code will look like this: “fscanf(in_file, “%[^\n]”
C program to Read File Line by Line
To run this program, we need one text file with the name Readme.txt in the same folder where we have our code.The content of the file is:
Hello My name is
John
danny
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
const char* filename = "Readme.txt";
int main(int argc, char *argv[])
{
FILE *in_file = fopen(filename, "r");
if (!in_file)
{
perror("fopen");
return 0;
}
struct stat sb;
if (stat(filename, &sb) == -1) {
perror("stat");
return 0;
}
char *textRead = malloc(sb.st_size);
int i = 1;
while (fscanf(in_file, "%[^\n] ", textRead) != EOF)
{
printf("Line %d is %s\n",i, textRead);
i++;
}
fclose(in_file);
return 0;
}
Output
Line 1 is Hello My name is
Line 2 is John
Line 3 is danny