Ugenz Academy/Tutorial

Filehandling

13 min read2,500 words

Reading progress

Keep learning

File Handling in C++

1. Introduction

File Handling in C++ is used to create, read, write, update, and manage data stored in files.

Normally, data stored in variables is lost when the program ends. Files allow us to store data permanently on a computer.

For example:

  • Student records
  • Employee information
  • Bank transaction records
  • Reports
  • Configuration data
  • Application logs

2. Why is File Handling Used?

File handling is useful because it allows programs to:

  • Store data permanently
  • Read existing data
  • Write new data
  • Add data to existing files
  • Update stored information
  • Process large amounts of data
  • Share data between program executions

3. File Streams in C++

C++ provides file stream classes through the <fstream> header.

The three main classes are:

ClassPurpose
ofstreamUsed to write data to a file
ifstreamUsed to read data from a file
fstreamUsed for both reading and writing

Include the header:

#include <fstream>

4. ofstream

ofstream stands for output file stream.

It is mainly used to write data into a file.

Syntax

ofstream file; file.open("filename.txt");

Example

#include <iostream> #include <fstream> using namespace std; int main() { ofstream file; file.open("data.txt"); file << "Hello C++"; file << "\nFile Handling"; file.close(); cout << "Data written successfully."; return 0; }

Output

Data written successfully.

The program creates data.txt and stores:

Hello C++ File Handling

5. ifstream

ifstream stands for input file stream.

It is used to read data from a file.

Example

Suppose data.txt contains:

Hello C++ File Handling

Program:

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file; file.open("data.txt"); string text; while (getline(file, text)) { cout << text << endl; } file.close(); return 0; }

Output

Hello C++ File Handling

6. fstream

fstream can be used for both reading and writing.

Example

#include <iostream> #include <fstream> using namespace std; int main() { fstream file; file.open("data.txt", ios::out); file << "Welcome to C++ File Handling"; file.close(); cout << "Data written successfully."; return 0; }

7. Opening a File

A file can be opened using the open() function.

Syntax

file.open("filename.txt", mode);

Example

ofstream file; file.open("student.txt");

The default mode for ofstream is generally output mode.

8. Closing a File

After completing file operations, the file should be closed.

Syntax

file.close();

Example

ofstream file("data.txt"); file << "Hello"; file.close();

Closing a file:

  • Releases system resources
  • Ensures buffered data is written
  • Prevents unnecessary file access

9. File Opening Modes

C++ provides different file-opening modes.

ModeMeaning
ios::inOpen for reading
ios::outOpen for writing
ios::appAppend data at the end
ios::ateOpen and move to the end
ios::truncDelete existing contents
ios::binaryOpen in binary mode

10. ios::out

ios::out opens a file for writing.

#include <fstream> using namespace std; int main() { ofstream file("data.txt", ios::out); file << "Hello C++"; file.close(); return 0; }

11. ios::in

ios::in opens a file for reading.

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt", ios::in); string text; while (getline(file, text)) { cout << text << endl; } file.close(); return 0; }

12. ios::app

ios::app means append.

New data is added to the end of the existing file without removing the old data.

Example

#include <fstream> using namespace std; int main() { ofstream file("data.txt", ios::app); file << "\nNew line added."; file.close(); return 0; }

If the file previously contained:

Hello C++

After running the program:

Hello C++ New line added.

13. ios::trunc

ios::trunc removes the existing contents of a file when it is opened for output.

ofstream file("data.txt", ios::out | ios::trunc); file << "New Data"; file.close();

Previous content is replaced.

14. Reading a File Line by Line

The getline() function is commonly used to read a file line by line.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("student.txt"); string line; while (getline(file, line)) { cout << line << endl; } file.close(); return 0; }

15. Reading Word by Word

The extraction operator >> can be used to read data word by word.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); string word; while (file >> word) { cout << word << endl; } file.close(); return 0; }

If the file contains:

C++ is easy to learn

Output:

C++ is easy to learn

16. Checking Whether a File Opened Successfully

It is good practice to check whether a file was successfully opened.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); if (!file) { cout << "File could not be opened."; return 1; } cout << "File opened successfully."; file.close(); return 0; }

Output

File opened successfully.

17. Using is_open()

The is_open() function checks whether a file is open.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); if (file.is_open()) { cout << "File opened successfully."; } else { cout << "Unable to open file."; } file.close(); return 0; }

18. Writing Multiple Values

A file can contain different types of data.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("student.txt"); string name = "Anuradha"; int age = 22; double marks = 85.5; file << "Name: " << name << endl; file << "Age: " << age << endl; file << "Marks: " << marks << endl; file.close(); return 0; }

The file contains:

Name: Anuradha Age: 22 Marks: 85.5

19. Append Data to a File

Appending means adding new information without deleting existing information.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("student.txt", ios::app); file << "\nCourse: BSc CSIT"; file.close(); cout << "Data appended successfully."; return 0; }

20. Reading and Writing Using fstream

fstream can perform both operations.

Example

#include <iostream> #include <fstream> using namespace std; int main() { fstream file; file.open("data.txt", ios::out); file << "Hello C++"; file.close(); file.open("data.txt", ios::in); string text; getline(file, text); cout << text; file.close(); return 0; }

Output

Hello C++

21. Combining File Modes

Multiple file modes can be combined using the | operator.

Example

fstream file; file.open("data.txt", ios::in | ios::out);

This opens the file for both reading and writing.

Another example:

ofstream file("data.txt", ios::out | ios::app);

This opens the file for writing and appending.

22. File Pointers

C++ uses file pointers to keep track of the current position in a file.

There are two important pointers:

PointerPurpose
Get pointerPosition used for reading
Put pointerPosition used for writing

Functions commonly used with file pointers include:

tellg() seekg() tellp() seekp()

23. tellg()

tellg() returns the current position of the get pointer.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); cout << "Position: " << file.tellg(); file.close(); return 0; }

24. tellp()

tellp() returns the current position of the put pointer.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("data.txt"); file << "Hello"; cout << "Position: " << file.tellp(); file.close(); return 0; }

25. seekg()

seekg() moves the get pointer to a specific position.

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); file.seekg(5); string text; getline(file, text); cout << text; file.close(); return 0; }

26. seekp()

seekp() moves the put pointer to a specific position.

Example

#include <fstream> using namespace std; int main() { ofstream file("data.txt"); file << "Hello World"; file.seekp(6); file << "C++"; file.close(); return 0; }

27. Binary File Handling

Binary files store data in binary format rather than normal human-readable text.

Binary file operations commonly use:

write() read()

Example

#include <iostream> #include <fstream> using namespace std; int main() { int number = 100; ofstream file("number.dat", ios::binary); file.write(reinterpret_cast<char*>(&number), sizeof(number)); file.close(); cout << "Data written successfully."; return 0; }

28. Reading a Binary File

Example

#include <iostream> #include <fstream> using namespace std; int main() { int number; ifstream file("number.dat", ios::binary); file.read(reinterpret_cast<char*>(&number), sizeof(number)); cout << "Number: " << number; file.close(); return 0; }

Output

Number: 100

29. Text File vs Binary File

Text FileBinary File
Stores human-readable textStores data in binary representation
Easy to read manuallyUsually not human-readable
Often larger for numeric dataCan be more compact
Uses text operationsUses read() and write()
Examples: .txt, .csvExamples: .dat, .bin

30. File Handling with Structures

Structures can also be stored in files.

Example

#include <iostream> #include <fstream> using namespace std; struct Student { int id; char name[50]; float marks; }; int main() { Student s = {101, "Anuradha", 85.5}; ofstream file("student.dat", ios::binary); file.write(reinterpret_cast<char*>(&s), sizeof(s)); file.close(); cout << "Student data saved."; return 0; }

31. Reading Structure from Binary File

#include <iostream> #include <fstream> using namespace std; struct Student { int id; char name[50]; float marks; }; int main() { Student s; ifstream file("student.dat", ios::binary); file.read(reinterpret_cast<char*>(&s), sizeof(s)); cout << "ID: " << s.id << endl; cout << "Name: " << s.name << endl; cout << "Marks: " << s.marks << endl; file.close(); return 0; }

Output

ID: 101 Name: Anuradha Marks: 85.5

32. File Error States

C++ streams provide functions to check file errors.

FunctionMeaning
good()No error has occurred
eof()End of file reached
fail()Operation failed
bad()Serious I/O error
clear()Clears error flags

Example

#include <iostream> #include <fstream> using namespace std; int main() { ifstream file("data.txt"); if (file.fail()) { cout << "File operation failed."; } file.close(); return 0; }

33. Checking End of File

eof() checks whether the end of the file has been reached.

A common and correct pattern for reading lines is:

string line; while (getline(file, line)) { cout << line << endl; }

This is generally preferred over:

while (!file.eof()) { // ... }

because eof() becomes true only after an attempted read reaches the end.

34. Complete Student File Example

This example writes and then reads student information.

#include <iostream> #include <fstream> using namespace std; int main() { // Writing data ofstream outFile("student.txt"); outFile << "Name: Anuradha" << endl; outFile << "Course: BSc CSIT" << endl; outFile << "College: Rajarshi Janak University" << endl; outFile.close(); // Reading data ifstream inFile("student.txt"); string line; while (getline(inFile, line)) { cout << line << endl; } inFile.close(); return 0; }

Output

Name: Anuradha Course: BSc CSIT College: Rajarshi Janak University

35. Real-Life Example

File handling is commonly used in applications such as:

Student Management System

A program can store:

Student ID Student Name Course Marks Address

in a file.

For example:

101, Anuradha, BSc CSIT, 85 102, Ram, BSc CSIT, 78 103, Sita, BSc CSIT, 91

The program can then:

  1. Add a student
  2. Save student information
  3. Read student information
  4. Search for a student
  5. Update information
  6. Generate reports

36. Advantages of File Handling

1. Permanent Storage

Data remains available after the program terminates.

2. Large Data Storage

Files can store large amounts of information.

3. Data Reusability

Stored data can be used again later.

4. Easy Data Sharing

Files can be transferred between programs and systems.

5. Backup

Important information can be saved for backup purposes.

6. Data Management

Files can be used to organize and manage application data.

37. Disadvantages of File Handling

1. Slower Than Memory

File operations are generally slower than accessing data already in memory.

2. File Corruption

Unexpected failures can potentially damage stored data.

3. Security Issues

Sensitive files need appropriate protection.

4. More Programming Work

Reading, writing, searching, and updating files require additional code.

5. Storage Dependency

The program depends on available storage and file permissions.

38. Important File Handling Functions

FunctionPurpose
open()Opens a file
close()Closes a file
is_open()Checks whether a file is open
getline()Reads a line
read()Reads binary data
write()Writes binary data
tellg()Gets reading position
tellp()Gets writing position
seekg()Changes reading position
seekp()Changes writing position
eof()Checks end of file
good()Checks stream state
fail()Checks operation failure
clear()Clears stream error flags

39. File Handling Classes Summary

C++ File Handling | +------------+------------+ | | | ofstream ifstream fstream | | | Writing Reading Read + Write

40. Key Points

  • File handling is used to store data permanently.
  • C++ provides file handling through the <fstream> header.
  • ofstream is mainly used for writing.
  • ifstream is mainly used for reading.
  • fstream supports both reading and writing.
  • open() opens a file.
  • close() closes a file.
  • ios::app adds data at the end of a file.
  • ios::in opens a file for reading.
  • ios::out opens a file for writing.
  • ios::binary is used for binary files.
  • getline() reads a complete line.
  • read() and write() are commonly used for binary data.
  • Always check whether a file was opened successfully.

41. Summary

File Handling in C++ allows programs to store and retrieve information from files.

The most important classes are:

ofstream → Write ifstream → Read fstream → Read + Write

Basic writing:

ofstream file("data.txt"); file << "Hello C++"; file.close();

Basic reading:

ifstream file("data.txt"); string line; while (getline(file, line)) { cout << line << endl; } file.close();

File handling is an important part of C++ because it allows applications to save, retrieve, update, and manage data permanently.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy