📂 File Handling in C Programming – Complete Beginner to Advanced Guide (With Programs, Viva, MCQs & Interview Questions)


🔹 Introduction

File handling in C allows us to store data permanently in files instead of temporary memory (RAM).

Until now, all our programs used variables that stored data temporarily.
But what if we want to:

  • Save student records

  • Store user login data

  • Maintain transaction history

  • Create reports

That’s where File Handling comes in.


🔹 Why File Handling is Important?

  • Stores data permanently

  • Helps in real-world applications

  • Required for projects

  • Very important for exams & interviews


🔹 What is a File in C?

A file is a collection of data stored on a storage device like:

  • Hard Disk

  • SSD

  • USB

In C, we use a pointer of type FILE to work with files.


🔹 File Pointer in C

Before working with files, we must declare a file pointer.

Syntax:

FILE *fp;   // Declare a file pointer to access and manage files

This pointer will point to the file we open.


🔹 Opening a File – fopen()

Syntax:

fp = fopen("filename.txt", "mode");   // Open a file with specified name and mode, and store its address in fp

Example:

fp = fopen("data.txt", "r");   // Open "data.txt" in read mode and store the file pointer in fp


🔹 File Modes

Mode Meaning
r Open for reading
w Open for writing (creates new file)
a Open for appending
r+ Read and write
w+ Write and read
a+ Append and read

🔹 Closing a File – fclose()

Syntax:

fclose(fp);   // Close the file associated with file pointer fp

Always close the file after use.


🔹 Writing to a File – fprintf()

Example Program

#include <stdio.h> // Include standard input-output header file int main() { // Main function where program execution begins FILE *fp; // Declare a file pointer variable fp = fopen("data.txt", "w"); // Open (or create) file "data.txt" in write mode fprintf(fp, "Hello Krishna!\n"); // Write first line into the file fprintf(fp, "Welcome to File Handling in C."); // Write second line into the file fclose(fp); // Close the file and free associated resources return 0; // Return 0 to indicate successful execution } // End of main function

This program creates a file and writes data into it.


🔹 Reading from a File – fscanf()

Example Program

#include <stdio.h>      // Includes standard input-output header file for file functions

int main() {            // Main function where program execution starts

    FILE *fp;           // Declare a file pointer to manage file operations
    char str[100];      // Declare a character array to store data read from file

    fp = fopen("data.txt", "r");   // Open the file "data.txt" in read mode

    fscanf(fp, "%s", str);         // Read a string from the file and store it in 'str'

    printf("Data: %s", str);       // Print the data read from the file to the screen

    fclose(fp);                    // Close the file to free resources

    return 0;                      // End the program successfully
}



🔹 Character I/O Functions

fgetc() – Read one character

fputc() – Write one character

Example:

fputc('A', fp); // Write character 'A' to the file pointed by fp
char ch = fgetc(fp); // Read a single character from the file and store it in variable ch

🔹 Binary File Functions

fwrite() – Write binary data

fread() – Read binary data

Example:

fwrite(&num, sizeof(num), 1, fp); // Write 1 element of size sizeof(num) from address of num into the file fread(&num, sizeof(num), 1, fp); // Read 1 element of size sizeof(num) from file into address of num

🔥 5 Practice Programs


🔥 1️⃣ Write Data to File

This program takes a student name from the user and writes it into a file named student.txt.

#include <stdio.h> // Include standard input-output header file int main() { // Main function where program execution begins FILE *fp; // Declare a file pointer variable char name[50]; // Declare character array to store student's name fp = fopen("student.txt", "w"); // Open (or create) "student.txt" in write mode if (fp == NULL) { // Check whether file opened successfully printf("Error opening file!"); // Display error message if file not opened return 1; // Exit program with error status } printf("Enter name: "); // Ask user to enter a name scanf("%s", name); // Read name from user and store in name array fprintf(fp, "%s", name); // Write the entered name into the file fclose(fp); // Close the file and release associated resources printf("Data written successfully!"); // Display success message return 0; // Return 0 to indicate successful program execution } // End of main function

🔥 2️⃣ Read Data from File

This program reads the student name stored in student.txt and displays it on the screen.

#include <stdio.h> // Include standard input-output header file int main() { // Main function where program execution starts FILE *fp; // Declare a file pointer variable char name[50]; // Declare character array to store data read from file fp = fopen("student.txt", "r"); // Open "student.txt" in read mode if (fp == NULL) { // Check whether the file opened successfully printf("File not found!"); // Display error message if file does not exist return 1; // Exit program with error status } fscanf(fp, "%s", name); // Read a string from the file and store it in name array printf("Student Name: %s", name); // Display the read data on the screen fclose(fp); // Close the file and release resources return 0; // Return 0 to indicate successful execution } // End of main function

🔥 3️⃣ Append Data to File

This program adds new student data to the end of the existing student.txt file without deleting old content.

#include <stdio.h> // Include standard input-output header file int main() { // Main function where execution begins FILE *fp; // Declare file pointer variable char name[50]; // Declare character array to store new name fp = fopen("student.txt", "a"); // Open "student.txt" in append mode (adds data at end) if (fp == NULL) { // Check whether file opened successfully printf("Error opening file!"); // Display error message if file not opened return 1; // Exit program with error status } printf("Enter another name: "); // Ask user to enter another name scanf("%s", name); // Read input from user and store in name array fprintf(fp, "\n%s", name); // Write new name at the end of the file (with new line) fclose(fp); // Close the file and release resources printf("Data appended successfully!"); // Display success message return 0; // Return 0 to indicate successful execution } // End of main function

🔥 4️⃣ Count Characters in File

This program counts the total number of characters present in student.txt using fgetc() until EOF.


#include <stdio.h> // Include standard input-output header file int main() { // Main function where program execution begins FILE *fp; // Declare file pointer variable char ch; // Declare variable to store each character read from file int count = 0; // Initialize counter variable to count characters fp = fopen("student.txt", "r"); // Open "student.txt" in read mode if (fp == NULL) { // Check whether file opened successfully printf("File not found!"); // Display error message if file does not exist return 1; // Exit program with error status } while ((ch = fgetc(fp)) != EOF) { // Read one character at a time until End Of File (EOF) count++; // Increase counter for each character read } printf("Total Characters: %d", count); // Display total number of characters fclose(fp); // Close the file and release associated resources return 0; // Return 0 to indicate successful execution } // End of main function

🔥 5️⃣ Copy One File to Another

This program copies all the contents from student.txt into another file named copy.txt.

#include <stdio.h> // Include standard input-output header file int main() { // Main function where program execution begins FILE *source, *target; // Declare two file pointers (source and target) char ch; // Declare variable to store each character source = fopen("student.txt", "r"); // Open source file in read mode target = fopen("copy.txt", "w"); // Open target file in write mode (creates new file) if (source == NULL || target == NULL) { // Check whether both files opened successfully printf("Error opening files!"); // Display error message if any file fails to open return 1; // Exit program with error status } while ((ch = fgetc(source)) != EOF) { // Read one character at a time from source until End Of File fputc(ch, target); // Write the read character into target file } printf("File copied successfully!"); // Display success message after copying fclose(source); // Close the source file fclose(target); // Close the target file return 0; // Return 0 to indicate successful execution } // End of main function

🎯 Viva Questions with Answers



1) What is File Handling in C?

File handling in C is a mechanism that allows a program to store data permanently in files and retrieve it later when required.

In normal programs, data stored in variables is temporary (stored in RAM).
Once the program ends, that data is lost.

File handling helps to:

  • Save data permanently (on hard disk)

  • Read previously stored data

  • Update or append new data

  • Share data between programs

C provides file handling support through the standard library:

#include <stdio.h> // Include standard input-output header file

Using file handling, we can:

  • Create a file

  • Open a file

  • Read from a file

  • Write to a file

  • Close a file

So, file handling enables permanent data storage using external files.


2) What is FILE in C?

FILE is a structure (struct) defined in the standard header file:

#include <stdio.h> // Include standard input-output header file

It is used internally by C to manage file operations.

When we write:

FILE *fp;
  • FILE → A predefined structure

  • *fp → A pointer to that structure

This structure stores information like:

  • File name

  • File mode (read/write/append)

  • Current position in file

  • Buffer information

  • Error status

We never directly access the structure fields — the system manages it internally.

So, FILE is a predefined structure used to control and manage file operations in C.


3) What is fopen()?

fopen() is a library function used to open a file.

Syntax:

FILE *fopen(const char *filename, const char *mode); // Function prototype to open a file with given name and mode, returns file pointer

Parameters:

  • filename → Name of the file

  • mode → Mode in which file is opened

Common Modes:

ModeMeaning
"r"Open file for reading
"w"Open file for writing (creates new or overwrites)
"a"Open file for appending
"r+"Read and write
"w+"Read and write (overwrite)
"a+"Read and append

Return Value:

  • Returns file pointer (FILE *) if successful

  • Returns NULL if file cannot be opened

Example:

FILE *fp; // Declare a file pointer variable
fp = fopen("data.txt", "r"); // Open "data.txt" in read mode and store the file address in fp

So, fopen() opens a file in a specified mode and returns a file pointer.


4) What happens if file is not found in "r" mode?

If we try to open a file in read mode ("r") and the file does not exist:

fp = fopen("data.txt", "r"); // Open "data.txt" in read mode and store the returned file pointer in fp

Then:

  • fopen() returns NULL

  • No file is created

  • Program must handle this error

Example:

if (fp == NULL) { // Check if file pointer is NULL (file failed to open) printf("File not found!"); // Display error message if file does not exist }

Important:

  • "r" mode does NOT create a new file.

  • It only opens an existing file.

  • If file doesn't exist → returns NULL.

So, in "r" mode, if file is missing, fopen() returns NULL and the program must handle it.


5) Why is fclose() Important?

fclose() is used to close an opened file.

Syntax:

fclose(fp); // Close the opened file and release associated system resources

Why it is important:

  1. Releases system resources (memory, buffers)

  2. Ensures data is properly written to file

  3. Prevents memory leaks

  4. Avoids file corruption

  5. Allows other programs to access the file safely

If we do not close a file:

  • Data may not be saved properly

  • Memory resources remain occupied

  • File may become unstable

So, fclose() safely closes the file and ensures proper resource management.


📝 5 MCQs

1) Which function opens a file?

A) open()
B) fopen() ✅
C) fileopen()
D) startfile()

fopen()fopen() is the standard C function used to open a file in a specified mode.


2) Which mode is used to append data?

A) r
B) w
C) a ✅
D) x

a"a" mode is used to append new data at the end of an existing file without deleting old data.


3) Which function reads binary data?

A) fread() ✅
B) fscanf()
C) printf()
D) read()

fread()fread() is used to read binary data from a file into memory.


4) fclose() is used to:

A) Delete file
B) Close file ✅
C) Read file
D) Open file

Close filefclose() properly closes an opened file and releases system resources.


5) If fopen fails, it returns:

A) 0
B) NULL ✅
C) -1
D) EOF

NULL → If fopen() fails to open a file, it returns NULL to indicate an error.


🚀 Advanced Interview Questions with Answers


1) Difference between text file and binary file?

Basis Text File Binary File
Data Format Stores data in human-readable format (characters) Stores data in raw binary format (0s and 1s)
Readability Can be opened and read in Notepad or text editor Cannot be understood in text editor
Storage Method Data is stored as ASCII/UTF characters Data is stored in actual memory representation
Speed Slower (due to format conversion) Faster (no conversion needed)
File Size Usually larger Usually smaller
Data Conversion Converts data into text form while writing No conversion, direct memory storage
Functions Used fprintf(), fscanf(), fgetc(), fputc() fread(), fwrite()
Modes Used "r", "w", "a" "rb", "wb", "ab"
Example Storage (100) Stored as '1' '0' '0' Stored as 4-byte binary integer
Usage Storing readable data like names, marks, reports Storing structures, images, executables


2) What is EOF?

EOF (End Of File) is a constant that indicates the end of a file has been reached.

  • Defined in <stdio.h>

  • Usually has value -1

  • Returned by functions like:

    • fgetc()

    • fscanf()

    • fread()

Example:

while ((ch = fgetc(fp)) != EOF) // Read one character at a time from file until End Of File (EOF) is reached

When there is no more data to read, fgetc() returns EOF.

So, EOF is a special indicator used to detect the end of file while reading.


3) How to Check if File Opened Successfully?

When we open a file using:

fp = fopen("data.txt", "r"); // Open "data.txt" in read mode and store the returned file pointer in fp

If file opens successfully:

  • fp contains a valid memory address.

If it fails:

  • fp becomes NULL.

So we check:

if (fp == NULL) { // Check if the file failed to open (file pointer is NULL) printf("Error opening file!"); // Display error message if file could not be opened }

Reasons for failure:

  • File does not exist (in "r" mode)

  • No permission

  • Invalid path

So, always check if file pointer is NULL to ensure file opened successfully.


4) What is Buffering in File Handling?

Buffering is a temporary memory area used to store data before it is written to or read from a file.

Instead of writing data directly to disk every time:

  • Data is first stored in a buffer (RAM memory)

  • Then written to disk in blocks

Why Buffering is Used:

  • Improves performance

  • Reduces disk access

  • Makes file operations faster

Example:
When using fprintf(), data may not immediately go to disk.
It stays in buffer until:

  • Buffer is full

  • fclose() is called

  • fflush() is called

So, buffering temporarily stores data in memory before actual disk operation to improve efficiency.


5) Difference Between fprintf() and fwrite()

Basis fprintf() fwrite()
Type of Data Written Writes formatted text data Writes raw binary data
File Type Used Used with text files Used with binary files
Data Conversion Converts data into readable text format No conversion, writes exact memory bytes
Speed Slower (due to formatting conversion) Faster (direct memory writing)
Human Readable Yes No
Usage Format Uses format specifiers like %d, %s Does not use format specifiers
Syntax Style fprintf(fp, "%d", num); fwrite(&num, sizeof(num), 1, fp);
Best Used For Writing readable reports, logs, text data Writing structures, objects, binary records
Storage of Integer 100 Stored as characters '1' '0' '0' Stored as binary representation (4 bytes)

Before concluding, let us quickly revise all the important file modes used in C programming.

The following table summarizes both text and binary file modes for quick reference.



Now that we understand file modes clearly, let us summarize what we have learned about File Handling in C.


🏁 Conclusion

File Handling in C is essential for real-world applications.
It allows programs to store, retrieve, and manage permanent data.

Mastering file handling will make you industry-ready and improve your interview performance.


📌 Keep Learning. Keep Coding. Keep Growing.

✨ Written by Krishna Popat
🌱 Founder, Learning Growth Hub

Comments

Popular posts from this blog

🌟 The Honest Journey of a Student: Learning, Failing, and Growing

“C Programming for Beginners: Master Variables, Data Types, and Memory (Bits Explained)”