Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Type Conversion C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Pass By Reference C Scope C Function Declaration C Functions Challenge C Math Functions C Inline Functions C Recursion C Function Pointers

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Structs Challenge C Nested Structures C Arrays of Structs C Structs & Pointers C Unions C typedef C Struct Padding

C Enums

C Enums

C Memory

C Memory Management C Allocate Memory C Access Memory C Reallocate Memory C Deallocate Memory C Structs and Memory C Memory Example C Memory Mistakes

C Errors

C Errors C Error Challenge C Debugging C NULL C Error Handling C Input Validation

C Problem Solving

C Problem Solving C Build the Logic C Edge Cases & Errors C Test Cases

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers C Command-Line Args

C DSA

C DSA Intro C Searching C Sorting C Stacks C Queues C Linked Lists C Trees C Hash Tables C Big O

C Projects

C Projects

C Cert

C Certificate

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A

C Read Files


Share

Read a File

In the previous chapter, we wrote to a file using w and a modes inside the fopen() function.

To read from a file, you can use the r mode:

Example

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

This opens filename.txt for reading.

Reading a file in C takes a few steps. We will guide you through them, one by one.

Next, we need to create a string that should be big enough to store a line of text from the file.

For example, let's create a string that can store up to 100 characters:

Example

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

In order to read the content of filename.txt, we can use the fgets() function.

The fgets() function takes three parameters:

Example

fgets(myString, 100, fptr);
  1. The first parameter specifies where to store the file content, which will be in the myString array we just created.
  2. The second parameter specifies the maximum size of data to read, which should match the size of myString (100).
  3. The third parameter requires a file pointer that is used to read the file (fptr in our example).

Now, we can print the string, which will output the content of the file:

Example

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

// Read the content and store it inside myString
fgets(myString, 100, fptr);

// Print the file content
printf("%s", myString);

// Close the file
fclose(fptr);
Hello World!
Run example »

Note: The fgets function only reads the first line of the file. If you remember, there were two lines of text in filename.txt.

To read every line of the file, you can use a while loop:

Example

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

// Read the content and print it
while(fgets(myString, 100, fptr)) {
  printf("%s", myString);
}

// Close the file
fclose(fptr);
Hello World!
Hi everybody!
Run example »

The loop reads one line at a time. When there are no more lines, fgets() returns NULL (no value), and the loop stops.



Good Practice

If you try to open a file for reading that does not exist, the fopen() function will return NULL.

Tip: As a good practice, we can use an if statement to test for NULL, and print some text instead (when the file does not exist):

Example

FILE *fptr;

// Open a file in read mode
fptr = fopen("loremipsum.txt", "r");

// Print some text if the file does not exist
if (fptr == NULL) {
  printf("Not able to open the file.");
} else {
  // Close the file (only if it was opened)
  fclose(fptr);
}

If the file does not exist, the following text is printed:

Not able to open the file.
Run example »

With this in mind, we can create more reliable code if we use our "read a file" example above again:

Example

If the file exists, read the content and print it. If the file does not exist, print a message:

FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

// If the file exists
if (fptr != NULL) {
  // Read the content and print it
  while (fgets(myString, 100, fptr)) {
    printf("%s", myString);
  }

  // Close the file
  fclose(fptr);
} else {
  // If the file does not exist
  printf("Not able to open the file.");
}
Hello World!
Hi everybody!
Run example »

Note: Only close a file with fclose() if it was opened. When fopen() returns NULL, there is no file to close, and fclose(NULL) can make the program crash. You will learn more about NULL in our NULL chapter.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.