1,680 points
10 5 2

Read file in c line by line

C is called the mother of languages, today we will discuss how to read file in C line by line. Such functions are important to understand. Reading files of different format are a necessary element of programming. We will discuss mainly two functions fgets() and getline() as reading files is a trivial problem in any programming language but C is a versatile language that provides such functions that help to read and use the file in the program as a necessary element.

The Importance of reading files in programs  #

Until the user will not saves the result of the program, it will be a useless thing to run a program every time, check the result, and then disperse it again and again. We need to store the result of the program to save time and usage of the computer. A computer program stores the results in form of variables and these variables are not permanent storage when the user will kill the program all results stored in the variables will be washed from the memory. Due to this loss a user needs to store those results permanently. Here the role of the file becomes not only important but strongly important. A user can store the results of the program in the form of a file to save them permanently in computer memory. The is not specific to C language but any other programming language.

C programming language functions that offer the facility to read files  #

There is a variety of functions available in C to read files. I will not jump into the details of every function. I will provide you with a brief overview of some most used functions and detail of two functions that are fgets() and getline().

The function fgetc()

The int fgetc(FILE *stream) function of the C library retrieves the next character (an unsigned char) from the stream that has been supplied and advances the position indicator for the stream. One character from the file can be read using this function. The function pointer at that moment points to characters that fgetc() reads. It advances the read position to the following character after each successful read and returns the character (ASCII value) that was taken from the stream. When there is no material to read or a failed read, this function always returns EOF (-1).

The function fscanf()

The int fscanf(FILE *stream, const char *format,...) function of the C library reads formatted input from a stream.

Similar to printf specifiers, fscanf() accepts formatting specifications, all of which are fully listed on this page. The sample input file is opened using the fopen() function call in the example below, and memory of the full file size is allocated to store the read stream into it. The format string "%[n] " is specified to read the file stream up until the new line character. When the input is finished, fscanf() returns EOF, so we run through a while loop and display each line one at a time.

The function fread()

Data from the provided stream is read into the array referred to by ptr by the C library function size t fread(void *ptr, size t size, size t nmemb, FILE *stream).

The function feof()

Using feof() returns true if the file pointer has reached the end of the file and accepts a file pointer as an argument.

Methods of C programming language used to read files  #

I have briefly explained a few mostly used functions of C used to read data from files. Now I will explain the detail of the two most used functions to read data from files in the C programming language.

The function getline()  #

A component of the C library is the getline() function. Getline() is a preferable choice because this function takes a string from the input stream as an input. Using a newline character as an example, the getline function reads a complete line from a stream. Make a stop character using the getline method to complete the input. Here is an example that will help you better understand how the getline() function in the C programming language works.


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

int main()


    char *buffer;
    size_t bufsize = 32;
    size_t characters;

    buffer = (char *)malloc(bufsize * sizeof(char));
    if( buffer == NULL)

        perror("Unable to allocate buffer");

    printf("Type something: ");
    characters = getline(&buffer,&bufsize,stdin);
    printf("%zu characters were read.\n",characters);
    printf("You typed: '%s'\n",buffer);



The function fgets()  #

The char *fgets(char *str, int n, FILE *stream) function of the C library reads a line from the given stream and inserts it into the string referred to by str. When (n-1) characters, the newline character, or the end of the file are read, or whichever occurs first, the program ends. Fortunately, using the fgets() function, we can both read text lines from a file or the standard input stream (). The memory that will be used as the read-line destination by the fgets() method must be provided by the caller code.

fgets(char *str, int n, FILE *stream)

int main()
    char string[20];
    FILE *fp;
    printf("The string is: %s",string);

    return 0;


The Conclusion   #

In this article, we have discussed the importance of files in programming languages, specifically with C language as our focused topic. We have discussed the available functions in C to read the file and get input from files. We discussed two functions in detail the fgets() and getline() functions in detail with examples. I am sure after reading this article will be able to write a program that the program read file in C line by line. In my viewpoint, the art of learning code and becoming a developer could not be achieved without understanding the role of files and the functions of programming languages which offer the feature of reading files or taking input from files.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

C++ read file line by line into vectors RickyGuo - Jul 13
How to Read a File line by line in Python umasivasu21 - Aug 2
C++ read file into char array Tsiyon Regassa - Jun 13
Python read file line by line into array Ferdy - Jul 19
C read from stdin until eof RickyGuo - Jul 18
How to print ASCII value in C Bushra Rubab - Sep 22
How to make Sum of digits at Even and Odd Places in C? Bushra Rubab - Sep 9
The function was not declared in this scope c++ AnkurRanpariyav - Aug 7
How to check if an array is empty in C++? AnkurRanpariyav - Aug 7
How to create the table in C++? AnkurRanpariyav - Aug 6
How to round off to 2 decimal places in C++? AnkurRanpariyav - Aug 6
Algorithm to calculate logarithms in C. Without math.h AnkurRanpariyav - Aug 5
How to iterate through a set in C++? AnkurRanpariyav - Aug 5
Check if the vector contains the given element or not in C++ AnkurRanpariyav - Aug 3
How to make text-based games in C++ AnkurRanpariyav - Aug 2
C++ nullptr was not declared in this scope cafe-coder45 - Jun 2
Qualified Name Is Not Allowed In Member Declaration in C++ JimCoder - May 29
The file will have its original line endings in your working directory Ankur Ranpariya 1 - Aug 21
Error: Enoent: No Such File Or Directory Open zhteja - Sep 19
C++ cstring to string sadmin - Sep 15