DigitalSanjiv

File Handling in C

File Handling in C Language With Examples | fopen(), fread(), fwrite()

File Handling in C Language

Want to store data permanently in C programs instead of losing it after program execution ends? File Handling in C Language allows programmers to create, read, write, update, and manage files efficiently using predefined functions available in the stdio.h header file.

Moreover, file handling helps developers build real-world software such as banking systems, student management applications, billing software, inventory systems, and employee databases.

Therefore, understanding file handling functions like fopen(), fclose(), fread(), fwrite(), fseek(), and rewind() is essential for every programming student and software developer who wants to build practical applications using C Language.

Before learning file handling, students should understand basic concepts like variables, loops, arrays, and functions in C Language.

What is File Handling in C Language?

File Handling in C Language is used to store, retrieve, update, and manage data permanently inside files. Unlike variables that store data temporarily in RAM, files preserve information even after the program closes.

File handling in C is the process of performing operations such as creating, opening, reading, writing, updating, and closing files using predefined library functions available in the stdio.h header file.

In practical software development, file handling is extremely important because almost every real-world application stores data in files or databases.

For example:

  • School software stores student records
  • Banking applications store transaction details
  • Billing systems save invoices
  • Inventory systems store stock information

Therefore, file handling forms the foundation of persistent data storage in C programming.

Why File Handling is Important in C

Many beginners initially learn variables and arrays. However, those techniques store data only during program execution.

Once the program ends:

  • all variables disappear
  • arrays lose values
  • memory gets cleared

File handling solves this problem.

Advantages of File Handling

  • Permanent data storage
  • Better record management
  • Faster data retrieval
  • Data sharing between programs
  • Efficient large-data processing
  • Useful for real-world projects

Additionally, file handling improves practical programming skills significantly.

Types of File Handling in C

There are mainly two types of file handling methods in C Language.

1. Standard I/O File Handling

Standard Input/Output uses functions from the stdio.h library.

These functions automatically manage:

  • buffering
  • formatting
  • memory handling
  • file streams

Common Standard I/O Functions

FunctionPurpose
fopen()Opens file
fclose()Closes file
fprintf()Writes formatted data
fscanf()Reads formatted data
fgets()Reads strings
fputs()Writes strings

2. System Level File Handling

System-level file handling directly communicates with the operating system using system calls.

Although it provides:

  • faster execution
  • low-level access
  • better control

it is more complex for beginners.

Therefore, most students start with standard I/O file handling.

File Pointer in C

A file pointer connects the program with the actual file stored on the disk.

Syntax

FILE *fp;

Here:

  • FILE is a predefined structure
  • fp is the file pointer

Without a file pointer, no file operation can be performed. File pointers work similarly to normal pointers used in memory management.

Practical Insight

During beginner programming classes, many students confuse normal pointers with file pointers. However, file pointers specifically point to file streams and contain information about:

  • file location
  • buffer
  • current position
  • file mode

What is fopen() Function in C

fopen() is a predefined function in C Language used to open files for reading, writing, appending, or updating. It returns a file pointer if successful; otherwise, it returns NULL.

The fopen() function opens a file in a specified mode.

Syntax

FILE *fopen(const char *filename, const char *mode);

Example Program

#include<stdio.h> 
int main()
{
   FILE *fp;     
   fp = fopen("student.txt", "w");     
   if(fp == NULL)    
     {        
        printf("File cannot be opened");    
     }    
    else    
     {        
       printf("File opened successfully");    
     }     
     fclose(fp);     
 return 0;
}

Output

File opened successfully

File Opening Modes in C

Different modes are used depending on file operations.

ModeDescription
rRead mode
wWrite mode
aAppend mode
r+Read and write
w+Read/write with overwrite
a+Read and append

Binary Modes

Adding b creates binary modes:

  • rb
  • wb
  • ab

Binary files are widely used in:

  • database systems
  • image processing
  • record management
  • software applications

fclose() Function in C

After file operations are completed, files must be closed properly.

Syntax

fclose(fp);

Why fclose() is Important

Closing files:

  • saves pending data
  • frees memory
  • releases resources
  • prevents corruption

Many beginners ignore this step initially. However, in larger applications, unclosed files can create memory leaks and resource issues.

Character Input and Output Functions

Character functions are simple and useful for beginners.

Writing Characters Using fputc()

Syntax

fputc(character, fp);

Example

fputc('A', fp);

Reading Characters Using fgetc()

Syntax

fgetc(fp);

Example

char ch;ch = fgetc(fp);

Character-by-character file reading often uses loops and conditional statements in C.

String File Handling Functions

String functions handle text line-by-line.

Writing Strings Using fputs()

fputs("Welcome to C Programming", fp);

Reading Strings Using fgets()

fgets(str, 50, fp);

These functions are commonly used in:

  • log files
  • reports
  • text processing applications

Functions like fgets() and fputs() are closely related to string handling concepts in C.

Formatted File Handling Functions

Formatted functions work similarly to printf() and scanf().

fprintf() Function

Syntax

fprintf(fp, "%d %s", id, name);

Example

fprintf(fp, "Roll No: %d", 101);

Formatted file handling functions works similar to formatted input and output in C

fscanf() Function

Syntax

fscanf(fp, "%d %s", &id, name);

These functions are useful in:

  • result systems
  • employee records
  • student databases

Binary File Handling in C

Binary files store data in machine-readable format instead of readable text. Binary file handling is commonly used with structures in C for record management systems.

Consequently:

  • execution becomes faster
  • storage size reduces
  • performance improves

Advantages of Binary Files

AdvantageExplanation
Faster processingNo conversion required
Less storage spaceCompact representation
Efficient record handlingUseful for structures
Better performanceIdeal for large data

fread() Function in C

The fread() function reads binary data blocks from files.

Syntax

fread(&data, sizeof(data), 1, fp);

Example

fread(&student, sizeof(student), 1, fp);

fwrite() Function in C

The fwrite() function writes binary data into files.

Syntax

fwrite(&data, sizeof(data), 1, fp);

Example

fwrite(&student, sizeof(student), 1, fp);

Random Access Functions in C

Random access allows direct access to any location inside a file.

This improves efficiency significantly in large applications.

ftell() Function

Returns the current file pointer position.

ftell(fp);

rewind() Function

Moves pointer to beginning of file.

rewind(fp);

fseek() Function

Moves file pointer to a specific location.

Syntax

fseek(fp, offset, origin);

Example

fseek(fp, 0, SEEK_END);

Difference Between Text File and Binary File

Text FileBinary File
Human readableMachine readable
SlowerFaster
Larger sizeSmaller size
Easy editingDifficult editing
Character storageBinary storage

Common Errors in File Handling

Many beginners repeatedly make these mistakes.

Common Mistakes

  • Forgetting NULL checks
  • Using wrong modes
  • Not closing files
  • Reading closed files
  • Incorrect pointer usage

Practical Teaching Observation

Students usually struggle more with:

  • binary files
  • file pointer positioning
  • append mode behavior

Therefore, regular practice with mini-projects is extremely important.

Mini Project Using File Handling in C

Student Record Management System

A beginner-friendly mini project can include:

  • Add student record
  • Search student
  • Delete record
  • Update record

This project helps learners understand:

  • persistent storage
  • record handling
  • binary files
  • random access

Moreover, project-based learning improves coding confidence much faster than theory alone.

File Handling Interview Questions in C

What is a file pointer in C?

A file pointer is a pointer used to manage and access files in C programming.

Difference Between fread() and fscanf()

fread()fscanf()
Binary readingFormatted reading
FasterSlower
Block dataText data

What is EOF in C?

EOF stands for End Of File. It indicates that no more data is available for reading.

What is Random Access File Handling?

Random access allows direct movement to any file position using functions like fseek() and rewind().

Users searching for file handling in C also explore:

  • Arrays in C Language
  • Functions in C
  • Pointers in C
  • Structures in C
  • Dynamic Memory Allocation
  • C Programming Interview Questions
  • Binary Search in C
  • Data Structures in C

External Resources

For deeper technical understanding:

Conclusion

File Handling in C Language is one of the most practical and essential concepts in programming because it enables permanent data storage and efficient record management. Furthermore, understanding functions such as fopen(), fclose(), fread(), fwrite(), fseek(), and rewind() helps programmers build real-world applications efficiently.

Although beginners initially find file handling slightly confusing, especially binary files and file pointers, regular practice with examples and mini-projects makes the concepts much easier. Therefore, every C programming learner should actively practice file handling programs to strengthen problem-solving abilities and software development skills.

Author Bio

Written by Sanjiv Kumar, an IT trainer, blogger, and digital educator with 23 years of experience in computer education, programming, SEO, digital marketing, Tally GST, and practical technology training. Through DigitalSanjiv, he shares beginner-friendly tutorials, real-world programming concepts, and career-focused digital learning resources for students and professionals across India.

Similar Topics :         Recursion in C            Preprocessor Directives in C                    File, Stream and Standard I/O

You may Also Like :    How to Generate Output in JavaScript              Discounts in Sales Invoices in Tally.ERP9        What is New in HTML5

Download Official TurboC  IDE cum Compiler from here

Frequently Asked Questions (FAQs)

What is file handling in C Language?

File handling in C is used to create, read, write, update, and manage files permanently using predefined functions.

Which header file is used for file handling?

The stdio.h header file is used for file handling in C programming.

What is fopen() in C?

fopen() opens files in different modes such as reading, writing, and appending.

Why are binary files faster?

Binary files store data in machine-readable format without conversion overhead.

Why is fclose() necessary?

fclose() saves pending data, releases resources, and prevents corruption.

1 thought on “File Handling in C Language With Examples | fopen(), fread(), fwrite()”

  1. Pingback: Dynamic Memory Allocation in C - DigitalSanjiv

Leave a Comment

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