C Tutorial



C Tutorial

File Handling in C

What Is File Handling In C?

File handling in C is a foundational aspect of programming, extending the life and reach of data beyond the execution lifecycle of the program. It allows us to create, read, write, and modify files stored on the system. File handling is a critical component in data persistence, providing a means for data to be stored and retrieved, even after the program has been terminated or the computer has been turned off.

Basics of File Handling in C

Before we jump into file handling in C, it's crucial to understand what a file is in the context of the C programming language.

What Is a File In C?

A file in C is a structured set of bytes stored on the system's secondary memory, such as the hard disk. It's a storage area where data can be held for later retrieval. This data can be anything from text to images or binary data.

Why Do We Need File Handling In C?

File handling in C is essential for several reasons. It allows programs to store information in a non-volatile storage medium. Data stored in files persist beyond the runtime of a program, enabling the possibility of data reusability. This means we can read, update, and manipulate stored data anytime, even long after the program that created the data has finished executing.

Types Of Files In a C Program

In C, there are two types of files that we commonly work with:

Text Files

Text files are human-readable and contain characters that can be interpreted as text. They are typically organised into lines separated by newline characters.

Binary Files

Binary files contain binary data that may not be human-readable. This data could represent anything, including images, audio files, executable programs, etc.

Operators/Functions That We Use For File Handling In C

The standard library in C includes functions for working with files. These file handling functions can be broadly divided into five categories:

  • Opening a File

  • Reading from a File

  • Writing to a File

  • Closing a File

  • Other Operations on Files

Opening A File In The Program – To Create And Edit Data

Before a file can be read or written, it must be opened using the fopen function. This function takes two arguments: the filename (including the path if necessary) and the mode. The mode determines what operations can be performed on the file.

FILE *fptr;
fptr = fopen("file.txt", "w");

In the example above, file.txt is the file we want to open, and "w" is the mode, which stands for write mode. If the file doesn't exist, it gets created.

How Do We Close A File?

After all operations on a file are completed, the file must be closed using the fclose function.


How Do We Read And Write The Data To The Text File?

To write data to a file, we use the fprintf function. To read data from a file, we use the fscanf function.

Example #1: Writing Data To The Text File In A Program

FILE *fptr;
fptr = fopen("file.txt", "w");
if(fptr == NULL)
fprintf(fptr,"%s","This is a file handling tutorial in C.");

In the above example, we first open file.txt in write mode. If the file cannot be opened (which may happen for various reasons), the program outputs an error message and exits. Otherwise, we write a string to the file using fprintf, and then close the file with fclose.

Example #2: Reading Information From The Text File In A Program

char str[100];
FILE *fptr;
if ((fptr = fopen("file.txt","r")) == NULL){
m    printf("Error! opening file");
printf("Data from the file:\n%s", str);

In this example, we open file.txt in read mode. If the file cannot be opened, the program outputs an error message and exits. Otherwise, we read a string from the file using fscanf and print it to the console. The file is then closed with fclose.

More Functions for File Handling in C

Apart from the fundamental file handling functions in C like fopen, fclose, fscanf, and fprintf, several other functions help with more specific tasks related to file handling. Understanding these functions can elevate your file handling skills in C.

getc and putc

getc and putc are functions for reading and writing individual characters to and from files. getc(FILE* stream) reads a character from a given file stream, while putc(int char, FILE* stream) writes a single character to the specified file stream. Here's a file handling in C example demonstrating their usage:

FILE *fptr;
char ch;

fptr = fopen("file.txt", "w");
putc('A', fptr);

fptr = fopen("file.txt", "r");
ch = getc(fptr);
printf("Character in file: %c", ch);

In this code, we first open file.txt in write mode and write the character 'A' to the file using putc. We then close the file, reopen it in read mode, read the character using getc, and print it.

fgets and fputs

fgets and fputs are similar to fscanf and fprintf, but they read and write strings rather than formatted data. Here's a file handling in C example:

FILE *fptr;
char str[50] = "File handling in C example.";

fptr = fopen("file.txt", "w");
fputs(str, fptr);

fptr = fopen("file.txt", "r");
fgets(str, 50, fptr);
printf("String in file: %s", str);

In this example, we write a string to a file using fputs and then read it back using fgets.

fseek, ftell and rewind

fseek is a function that sets the file position of the stream to a specific location. It takes three parameters - pointer to a FILE object, a long integer which is the number of bytes to offset, and the position from where offset is added.

ftell gives the current position in the file of a given file pointer. It returns a long int value representing the current position in the file.

rewind is used to set the file position to the beginning of the file. It takes a pointer to a FILE object of the file as the parameter and returns no value.

Here's an example using these functions:

FILE *fptr;
fptr = fopen("file.txt", "w");
fputs("This is a file handling tutorial in C.", fptr);
fseek(fptr, 7, SEEK_SET);
printf("Current position in file: %ld", ftell(fptr));
printf("Position after rewind: %ld", ftell(fptr));

In this file handling in C example, we first write a string to file.txt, then move the file position indicator 7 characters forward. We print the current position using ftell, then reset the position to the beginning of the file using rewind and print the position again.

Practice Problems On File Handling In C

Now that you're acquainted with the basics of file handling, it's time to apply your knowledge. Here are some problems to practise:

1. Count Characters, Words, and Lines in a Text File
Create a C program that reads a file and counts the number of characters, words, and lines in it.
Hint: You can read the file character by character using getc. Consider a word to be a sequence of characters separated by spaces, and a line to be a sequence of characters separated by newline ('\n') characters.

2. Copy One File to Another
Write a C program that copies the contents of one file to another file.
Hint: Open both files, one in read mode and the other in write mode. Read the source file character by character using getc and write to the destination file using putc.

3. Merge Two Text Files into a Third File
Write a program that merges the contents of two text files into a third file.
Hint: Similar to the above, but you'll need to read from two files sequentially and write to a third file.

4. Encrypt and Decrypt a Text File
Create a program that encrypts a text file by shifting each character by a fixed number (e.g., 3), creating a simple Caesar cipher. Then write another program that decrypts the file back to the original content.
Hint: For each character read from the file, add the shift amount before writing it to the encrypted file. For decryption, subtract the shift amount from each character.

5. Random Access with fseek
Write a program that writes the integers 1 through 100 to a binary file using fwrite. Then, use fseek to move to the beginning of the file, and read and print every 5th integer.
Hint: You can use fseek with SEEK_SET to move to any position in the file. Remember that fseek works with bytes, so you'll need to multiply the position of the integer by the size of an integer (sizeof(int)). 


Mastering file handling in C can open up a lot of opportunities for you to create more sophisticated and practical applications. By understanding and utilising file handling techniques, programmers can effectively manage and manipulate data stored in files, facilitating tasks such as data analysis, configuration management, and information exchange. 

Consider upGrad's Full Stack Software Development Bootcamp to bolster your C programming skills and propel your career opportunities in the development domain.


1. What is file handling in C?

File handling in C is a process that allows a C program to create, read, write, and modify files on the system's storage. It enables storing data for prolonged periods, extending beyond the execution cycle of the program.

2. What are the key file handling functions in C?

The primary file handling functions in C are fopen (to open a file), fprintf (to write to a file), fscanf (to read from a file), and fclose (to close a file). There are other functions as well, like fseek, ftell, and rewind for more advanced file operations.

3. What are text files and binary files in C?

Text files in C are human-readable files that store data in text format. They usually contain characters and strings arranged into lines. Binary files, on the other hand, are not typically human-readable and may contain any type of data encoded in binary form, including executable code, images, and numeric data.

4. What is the importance of file handling in C?

File handling in C is vital because it allows programs to persist data beyond their runtime. This implies that data can be stored, retrieved, and manipulated even after the program has stopped running or the computer has been shut off, which is critical for many real-world applications.

Leave a Reply

Your email address will not be published. Required fields are marked *