C Program to Read Content of a File
Last Updated :
13 May, 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// 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);
return 0;
}
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fptr; = fopen("file.txt", "r");
// 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;
}
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
#include <stdio.h>
int main() {
FILE *fptr = fopen("file.txt", "r");
// 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\t Age: %d\n", name, age);
}
fclose(fptr);
return 0;
}
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 EditorWhen 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 Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
Data Types in C Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc.Example:C++int number;The above statement declares a variable with name number that can store integer values.C is a statically type language where
5 min read
C Language Introduction C is a general-purpose procedural programming language initially developed by Dennis Ritchie in 1972 at Bell Laboratories of AT&T Labs. It was mainly created as a system programming language to write the UNIX operating system.Main features of CWhy Learn C?C is considered mother of all programmin
6 min read
C Arrays An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., as well as derived and user-defined data types such as pointers, structures, etc. Creating an Array in
7 min read
C Pointers A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it has the address where the value is stored in memory. This allows us to manipulate the data stored at a specific memory location without actually using its variable. It is the backbone of
9 min read
C Programs To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and
8 min read
Basics of File Handling in C File handling 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.Need of File Han
13 min read
Operators in C In C language, operators are symbols that represent some kind of operations to be performed. They are the basic components of the C programming. In this article, we will learn about all the operators in C with examples.What is an Operator in C?A C operator can be defined as the symbol that helps us
11 min read
Bitwise Operators in C In C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read