C Program to Read Content of a File
Last Updated :
07 Apr, 2025
In C, reading a file is a step-by-step process in which we first have to prepare the file only after which we can start reading. It involves opening the file, reading its data, and closing the file.
- Opening the File: Opening the file loads the file into the memory and connect the file to the program using file pointer. It is done fopen() function by passing its location in the storage and selecting the read mode as we will read the file.
- Reading the Data: After opening the file in read mode, different reading methods discussed below can be to read the file according to our preferences.
- Closing the File: After all the operations are done, it is a good practice to close the file using fclose() function to free the acquired memory.
Different Methods to Read a File in C
C programming language supports four pre-defined functions to read contents from a file, all of which are defined in <stdio.h> header:
Assume that the file.txt (file to read) contains the following data:

Let’s see how to use different reading methods one by one.
1. Using fgetc()
The fgetc() functions reads a single character pointed by the file pointer. On each successful read, it returns the character (ASCII value) read from the stream and advances the file pointer to the next character. It returns a constant EOF when there is no content to read or an unsuccessful read.
So, we can read the whole content of the file using this function by reading characters one by one till we encounter EOF.
Example:
C
//Driver Code Starts{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
//Driver Code Ends }
// Character that store the read
// character
char ch;
// Opening file in reading mode
FILE *fptr = fopen("file.txt", "r");
// Reading file character by character
while ((ch = fgetc(fptr)) != EOF)
printf("%c", ch);
// Closing the file
fclose(fptr);
//Driver Code Starts{
return 0;
}
//Driver Code Ends }
Output
GeeksforGeeks - A computer science portal for geeks
When to use fgetc()?
Reading file using fgetc() is useful for processing each character individually, such as counting specific characters or handling text encoding. It is also useful to print data when you don’t know anything about the file.
2. Using fgets()
The fgets() function is similar to the fgetc() but instead of a single character, it reads one string up to given number of characters at a time and stores it in the given string buffer. It returns the string if it is successfully read or returns NULL if failed.
Example:
C
//Driver Code Starts{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fptr; = fopen("file.txt", "r");
//Driver Code Ends }
// Buffer to store 50 characters at a time
char buff[50];
// Reading strings till fgets returns NULL
while (fgets(buff, 50, fptr)) {
printf("%s", buff);
};
fclose(fptr);
return 0;
//Driver Code Starts{
}
//Driver Code Ends }
Output
GeeksforGeeks - A computer science portal for geeks
When to use fgets()?
Reading file using fgets() is ideal for text files where lines need to be processed individually, such as reading configuration files or log files.
3. Using fscanf()
fscanf() is similar to scanf() that reads the input in the form of formatted string. It is much more powerful as compared to above methods as it can read, ignore, modify the type of data using scanset characters.
Consider the file.txt contains the following data:

Example:
C
//Driver Code Starts{
#include <stdio.h>
int main() {
FILE *fptr = fopen("file.txt", "r");
//Driver Code Ends }
// Variables for storing data
char name[100];
int age;
// Read data of file in specific format
while (fscanf(fptr, "%s %d", name, &age) == 2) {
printf("Name: %s Age: %d
", name, age);
}
fclose(fptr);
//Driver Code Starts{
return 0;
}
//Driver Code Ends }
Output
Name: Raman Age: 12
Name: Kunal Age: 25
Name: Vikas Age: 6
When to use fscanf()?
Reading a file using fscan() is best for structured data files, such as CSV files or files with fixed formats (e.g., reading a list of records with specific fields).
4. Using fread()
fread() makes it easier to read blocks of data from a file. For instance, in the case of reading a structure from the file, it becomes an easy job to read using fread because instead of looking for types, it reads the blocks of data from the file in the binary form.
If the objects read are not copy-able, then the behaviour is undefined and if the value of size or count is equal to zero, then this program will simply return 0.
Example:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Course {
int price;
char cname[100];
};
int main() {
// Open binary file in read mode
FILE *ptr = fopen("file.bin", "rb");
// Structure variable to
// store the file data
struct Course fileData;
// Start reading the data using fread
while (fread(&fileData, sizeof(struct
Course), 1, ptr)) {
printf("Course Name = %s Price = %d\n",
fileData.cname, fileData.price);
}
fclose(ptr);
return 0;
}
Output
Course Name = Data Structures and Algorithms - Self Paced Price = 6000
The binary file could look like this:

file.bin in Hex Editor
When to use fread()?
Reading a file using fread() is suitable for binary files or when you need to manipulate the entire file content at once, such as image files or raw data files.
Similar Reads
C Program to Print Contents of File
C language allows users to process the files in its programs. Reading a file is a step-by-step process in which we first have to prepare the file only after which we can start reading. In this article, we will learn how to read and print the contents of a file using C program. The simplest method to
4 min read
C program to reverse the content of the file and print it
Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples: Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has
3 min read
C Program to find size of a File
Given a text file, find its size in bytes. Examples: Input : file_name = "a.txt" Let "a.txt" contains "geeks" Output : 6 Bytes There are 5 bytes for 5 characters then an extra byte for end of file. Input : file_name = "a.txt" Let "a.txt" contains "geeks for geeks" Output : 16 Bytes The idea is to us
1 min read
C program to append content of one text file to another
Pre-requisite: File Handling in C Given the source and destination text files, the task is to append the content from source file to destination file and then display the content of the destination file.Examples: Input: file1.text This is line one in file1 Hello World. file2.text This is line one in
2 min read
How to Read From a File in C?
File handing in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. In this article,
2 min read
C Program to Read and Print All Files From a Zip File
To understand how to write a C program for reading and printing zip files, it's important to know what exactly a zip file is. At its core, a zip file contains one or more files compressed using specific compression algorithms.Including the compressed data of the files, the zip file contains meta and
6 min read
C program to read a range of bytes from file and print it to console
Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console. Functions Used: fopen(): Creation of a new file. The file is opened with attributes as âaâ or âa+â or âwâ or âw++â.fgetc(): Reading the characters from the file.fclose(): For clo
2 min read
C Program For Char to Int Conversion
Write a C program to convert the given numeric character to integer. Example: Input: '3'Output: 3Explanation: The character '3' is converted to the integer 3. Input: '9'Output: 9Explanation: The character '9' is converted to the integer 9. Different Methods to Convert the char to int in CThere are 3
3 min read
Lex program to search a word in a file
Problem: Write a Lex program to search a word in a file. Explanation: FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs
2 min read
How to Write a Command Line Program in C?
In C, we can provide arguments to a program while running it from the command line interface. These arguments are called command-line arguments. In this article, we will learn how to write a command line program in C. How to Write a Command Line Program in C? Command line arguments are passed to the
2 min read