codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

59 / 87 topics
55C++11 Features56Preprocessors and Macros57Templates (Function & Class Templates)58Namespaces59File Handling, Buffers, istream & ostream60Exception Handling, Asserts & Debugging61Multithreading
Tutorials/C++ Programming/File Handling, Buffers, istream & ostream
⚡C++ Programming

File Handling, Buffers, istream & ostream

Updated 2026-05-12
30 min read

File Handling, Buffers, istream & ostream

In this tutorial, you'll learn how to handle files in C++ using the ifstream, ofstream, and fstream classes. You'll explore file modes, reading from and writing to files, handling binary files, and understanding stream buffers. This knowledge is crucial for developing applications that require data persistence.

Introduction

File handling is a fundamental aspect of programming, allowing you to read from and write to files on your computer. In C++, the Standard Template Library (STL) provides several classes and functions to facilitate file operations. Understanding how to use these tools effectively will enable you to build robust applications that can manage data efficiently.

Core Content

File Streams in C++

C++ provides three main classes for file handling:

  1. ifstream: Used for reading from files.
  2. ofstream: Used for writing to files.
  3. fstream: Used for both reading and writing to files.

These classes are derived from the iostream class, which means they support input and output operations similar to those used with standard streams like cin and cout.

File Modes

File modes determine how a file is opened and what operations can be performed on it. Here are some common file modes:

ModeDescription
ios::inOpen for input operations.
ios::outOpen for output operations.
ios::appAppend to the end of the file.
ios::ateSeek to the end of the stream immediately after opening.
ios::truncTruncate the contents of the file if it already exists.
ios::binaryOpen in binary mode (as opposed to text mode).

Opening and Closing Files

To open a file, you can use the open() method of the file stream object. For example:

example.cpp
1#include <fstream>
2#include <iostream>
3
4int main() {
5 std::ifstream inputFile;
6 inputFile.open("input.txt");
7
8 if (!inputFile.is_open()) {
9 std::cerr << "Error opening file!" << std::endl;
10 return 1;
11 }
12
13 // File operations here
14
15 inputFile.close();
16 return 0;
17}
Output
Error opening file!

Tip

Always check if a file is successfully opened before performing any operations on it.

Reading from Files

You can read data from a file using various extraction operators (>>, getline(), etc.). Here's an example using the >> operator:

example.cpp
1#include <fstream>
2#include <iostream>
3
4int main() {
5 std::ifstream inputFile;
6 inputFile.open("input.txt");
7
8 if (!inputFile.is_open()) {
9 std::cerr << "Error opening file!" << std::endl;
10 return 1;
11 }
12
13 int number;
14 inputFile >> number;
15
16 std::cout << "Read number: " << number << std::endl;
17
18 inputFile.close();
19 return 0;
20}
Output
Read number: 42

Writing to Files

To write data to a file, you can use the << operator. Here's an example:

example.cpp
1#include <fstream>
2#include <iostream>
3
4int main() {
5 std::ofstream outputFile;
6 outputFile.open("output.txt");
7
8 if (!outputFile.is_open()) {
9 std::cerr << "Error opening file!" << std::endl;
10 return 1;
11 }
12
13 int number = 42;
14 outputFile << "Writing number: " << number;
15
16 outputFile.close();
17 return 0;
18}
Output
// No output, but the file 'output.txt' will contain:
// Writing number: 42

Binary Files

Binary files store data in its raw binary form, which is useful for storing non-textual data like images or executable files. Here's how to read and write binary files:

example.cpp
1#include <fstream>
2#include <iostream>
3
4int main() {
5 // Writing to a binary file
6 std::ofstream outputFile("binary.dat", std::ios::binary);
7 if (!outputFile.is_open()) {
8 std::cerr << "Error opening file!" << std::endl;
9 return 1;
10 }
11
12 int number = 42;
13 outputFile.write(reinterpret_cast<const char*>(&number), sizeof(number));
14
15 outputFile.close();
16
17 // Reading from a binary file
18 std::ifstream inputFile("binary.dat", std::ios::binary);
19 if (!inputFile.is_open()) {
20 std::cerr << "Error opening file!" << std::endl;
21 return 1;
22 }
23
24 int readNumber;
25 inputFile.read(reinterpret_cast<char*>(&readNumber), sizeof(readNumber));
26
27 std::cout << "Read number: " << readNumber << std::endl;
28
29 inputFile.close();
30 return 0;
31}
Output
Read number: 42

Stream Buffers

Stream buffers are used to manage the flow of data between streams and files. You can access and manipulate stream buffers using the rdbuf() method. Here's an example:

example.cpp
1#include <fstream>
2#include <iostream>
3#include <sstream>
4
5int main() {
6 std::ifstream inputFile("input.txt");
7 if (!inputFile.is_open()) {
8 std::cerr << "Error opening file!" << std::endl;
9 return 1;
10 }
11
12 // Create a string stream
13 std::stringstream buffer;
14
15 // Redirect the input file's buffer to the stringstream
16 buffer.rdbuf(inputFile.rdbuf());
17
18 std::string line;
19 while (std::getline(buffer, line)) {
20 std::cout << "Line: " << line << std::endl;
21 }
22
23 inputFile.close();
24 return 0;
25}
Output
Line: Hello, World!
Line: This is a test.

Warning

Always close files after you're done with them to free up resources.

Practical Example

Let's create a complete program that reads data from one file, processes it, and writes the results to another file.

example.cpp
1#include <fstream>
2#include <iostream>
3#include <string>
4
5int main() {
6 std::ifstream inputFile("input.txt");
7 if (!inputFile.is_open()) {
8 std::cerr << "Error opening input file!" << std::endl;
9 return 1;
10 }
11
12 std::ofstream outputFile("output.txt");
13 if (!outputFile.is_open()) {
14 std::cerr << "Error opening output file!" << std::endl;
15 inputFile.close();
16 return 1;
17 }
18
19 std::string line;
20 while (std::getline(inputFile, line)) {
21 // Process the line
22 outputFile << "Processed: " << line << std::endl;
23 }
24
25 inputFile.close();
26 outputFile.close();
27 return 0;
28}
Terminal
$ g++ example.cpp -o example
$ ./example
Output
// No output, but the file 'output.txt' will contain:
// Processed: Hello, World!
// Processed: This is a test.

Summary

  • Use ifstream, ofstream, and fstream for reading from and writing to files.
  • File modes like ios::in, ios::out, ios::app, etc., control how files are opened.
  • Always check if a file is successfully opened before performing operations on it.
  • Binary files store data in its raw binary form, useful for non-textual data.
  • Stream buffers manage the flow of data between streams and files.

What's Next?

In the next tutorial, you'll learn about exception handling, asserts, and debugging techniques. These tools will help you write more robust and error-free C++ programs. Stay tuned!


PreviousNamespacesNext Exception Handling, Asserts & Debugging

Recommended Gear

NamespacesException Handling, Asserts & Debugging