C Read Text File

Summary: in this tutorial, you will learn how to read from a text file line by line using standard I/O functions.

C Read Text File Steps

In order to read from a text file, you follow the steps below:

  • First, open the text file using the fopen() function.
  • Second, use the function fgets() to read text from the stream and store it as a string. The newline or EOF character makes the fgets() function stop reading so you can check the newline or EOF file character to read the whole line.
  • Third, close the text file using the fclose() function.

C Read Text File Example

Below is the source code of reading a text file line by line and output it to the screen.

/*
 * File:   main.c
 * Author: zentut.com
 * Description: Read text file line by line and output it to
 *              the screen.
 */

#include <stdio.h>

#define MAXCHAR 1000
int main() {
    FILE *fp;
    char str[MAXCHAR];
    char* filename = "c:\\temp\\test.txt";

    fp = fopen(filename, "r");
    if (fp == NULL){
        printf("Could not open file %s",filename);
        return 1;
    }
    while (fgets(str, MAXCHAR, fp) != NULL)
        printf("%s", str);
    fclose(fp);
    return 0;
}

In this tutorial, you’ve learned how to read from a text file using C standard I/O function.