How to Read Text file in C

How to Read Text file in C

Hello everyone, in this article we are going to see how can we read a file until the end and assign line by line to a variaable in C programming language with an example.

Let's get started.

First we are going to need below libraries. So include them:

#include <stdio.h>
Now rest of codes are will be in int main( void ) { ... } function.
First we request from user to specify the file

    char filePath[100];
    printf( "Enter file or drag file here to get file path :");
    gets( filePath );
Then we load inputted file path to the FILE structure to read
also we need a variable to read the text line by line
Also we can count how many lines do we have in text file

char const* const fileName = filePath; 
FILE* file = fopen(fileName, "r");

char line[1000];

char c;
int lineCount = 0;
Now we check the text file is correct and count the newlines

    for (c = getc(file); c != EOF; c = getc(file))
            if (c == '\n')
Here we clear the related pointer and reload the file

    file = fopen(fileName, "r");
Here you can make some controls on the characters EOF = end of file, You can make this control with different ways you can use ASCII encoding or whatever you want

for (c = getc(file); c != EOF; c = getc(file)){
       if (!(c == '0' || c == '1' || c == '2'   c == 'a' || c == 'b' || c == 'c' ||c == '\n')){
           return 0;
Again we clear the related pointer and reload the file.

    file = fopen(fileName, "r");
Lastly we print all text line by line and close the file when operation is completed

    int i = 0;
    while (fgets(line, sizeof(line), file)) {
        printf("Line %d : %s", i, line);
I have commented the control section to show you that the example is working. Do not forget there when you are in need.
Below image you can see the example output: Reading Text file in C example output

That is all in this article.

Burak Hamdi TUFAN.


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!


  • There is no comment. Be the owner of first comment...