Open In App

C Program to Read Content of a File

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

  1. 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.
  2. 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.
  3. 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:

dataWritten

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:

formatted-file-reading

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:

binaryFile

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.



Next Article

Similar Reads