Read & Display a Text File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Read and Display the Contents of a Text File

In this tutorial, you'll learn how to read a text file and display its contents on the console using the C programming language. This is the natural companion to Assignment 1 (creating and writing a file). The program opens the file in read mode, reads it line by line with fgets(), and prints each line. It's the foundation for almost every other file-handling program — counting words, searching, sorting, merging, and more.

C program to read and display the contents of a text file using fopen, fgets, and fclose, with step-by-step explanation.

📝 Problem Statement

Write a program in C to read and display the contents of a text file.

⚙️ How the Program Works

The program follows the standard read lifecycle:

  1. Ask for the filename (or hard-code it) and store it in a character array.
  2. Open the file in read mode with fopen("filename.txt", "r") and check for NULL.
  3. Read line by line using fgets() into a buffer. The loop ends when fgets returns NULL (end of file or read error).
  4. Print each line to the console with printf() or fputs().
  5. Close the file with fclose() to release the handle.

💻 Complete C Program

#include <stdio.h> int main(void) { FILE *fp; char filename[100]; char line[1024]; printf("Enter the filename to read: "); scanf("%99s", filename); /* Open the file in read mode */ fp = fopen(filename, "r"); if (fp == NULL) { printf("Error: Could not open file '%s'.\n", filename); return 1; } printf("\n--- Contents of %s ---\n\n", filename); /* Read one line at a time until end of file */ while (fgets(line, sizeof(line), fp) != NULL) { printf("%s", line); } printf("\n--- End of file ---\n"); fclose(fp); return 0; }

🖥️ Sample Output

Assume sample.txt contains the following lines:

Contents of sample.txt: Hello, World!
This text was written using fprintf.
File handling in C is fun!

Running the program:

Console: Enter the filename to read: sample.txt

--- Contents of sample.txt ---

Hello, World!
This text was written using fprintf.
File handling in C is fun!

--- End of file ---

🔍 Line-by-Line Explanation

Line / Code Explanation
char line[1024]; A buffer large enough to hold one line of text. 1024 bytes is enough for typical lines; use a larger buffer if your file has long lines.
scanf("%99s", filename) Reads the filename without spaces. %99s caps the input at 99 characters to avoid a buffer overflow.
fopen(filename, "r") Opens the file for reading. Returns NULL if the file doesn't exist or cannot be read.
fgets(line, sizeof(line), fp) Reads up to sizeof(line) - 1 characters or until a newline, whichever comes first. Returns NULL at end of file.
printf("%s", line) Prints the line. fgets keeps the trailing newline, so %s alone produces correct output.
fclose(fp) Releases the file handle. Always call this when done.
⚠️ Important: fgets stops at the newline or when the buffer is nearly full — whichever comes first. If a line is longer than 1023 characters, it will be returned in multiple chunks. The output will still be correct, but each chunk is treated as a separate iteration.

🔁 Other Ways to Read a File

fgets is the most common approach, but C gives you a few other options, each suited to a different task:

Function Reads Best for
fgets() One line at a time Displaying, searching, or processing line-based text
fgetc() One character at a time Counting characters, converting case, encrypting
fscanf() Formatted tokens (words, numbers) Reading structured text like CSVs or numeric data
fread() Raw bytes Binary files (see Assignments 7 and 8)

Here is the same task using fgetc — one character at a time. It's a bit more verbose but easier to adapt for character-level processing:

#include <stdio.h> int main(void) { FILE *fp; char filename[100]; int ch; printf("Enter the filename to read: "); scanf("%99s", filename); fp = fopen(filename, "r"); if (fp == NULL) { printf("Error: Could not open file.\n"); return 1; } /* fgetc returns int (not char) so EOF is distinguishable */ while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); return 0; }

Note the int ch — fgetc returns int, not char, so that EOF (-1) can be distinguished from the byte value 255. Declaring ch as char is a classic bug.

🐛 Common Pitfalls

  • Declaring ch as char: When using fgetc, always declare the receiving variable as int so EOF is detected correctly.
  • Forgetting the NULL check: A missing file causes a crash on the first read.
  • Buffer too small: If a line exceeds the buffer, fgets returns it in pieces. For very long lines, either enlarge the buffer or use fgetc.
  • Not closing the file: Skipping fclose leaks file descriptors and may leave buffered data unflushed.

💡 Tips & Best Practices

  • Use %99s (or the appropriate width) with scanf to prevent buffer overflows.
  • If you need the filename to contain spaces, use fgets to read it and strip the trailing newline.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type mismatches and unused variables.
  • When displaying a file on Windows, note that fgets in text mode converts \r\n to \n for you.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 1. Create a New Text File and Write Text in It
  • 2. Search for a Specific Word in a Text File
  • 5. Count Characters, Words, and Lines in a Text File
  • 15. Copy the Contents of One Text File into Another
  • File Handling in C — Introduction
  • Files FAQ

Previous Problem: -->> 3. Append Data to an Existing Binary File   ||   Next Problem: -->> 5. Count Characters, Words, and Lines in a Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.