C++ / C++ File I/O and Streams

Reading and Writing Files with Streams

In this tutorial, you'll learn how to use streams in C++ to read from and write to files. We'll cover the basic operations as well as some advanced techniques.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers file handling and working with streams in C++.

Introduction

In this tutorial, you will learn how to use streams in C++ to read and write files. Specifically, we will cover the use of ifstream (input file stream) and ofstream (output file stream) classes provided by the C++ Standard Library.

By the end of this tutorial, you will be able to:

  • Understand the concept of streams in C++
  • Read data from a file using ifstream
  • Write data to a file using ofstream
  • Implement advanced file handling techniques

Prerequisites: Basic knowledge of C++ programming is required to fully understand the concepts explained in this tutorial.

Step-by-Step Guide

In C++, a stream is a sequence of bytes where we can write or read data. A file stream is just a stream associated with a file.

Reading from a File

Use the ifstream class to read data from a file. Here's how to do it:

  1. Create an object of the ifstream class.
  2. Use the open() function to open a file.
  3. Use the >> operator to read data from the file.
  4. Close the file using the close() function.

Writing to a File

Use the ofstream class to write data to a file. Here's how to do it:

  1. Create an object of the ofstream class.
  2. Use the open() function to open a file.
  3. Use the << operator to write data to the file.
  4. Close the file using the close() function.

Code Examples

Let's see some practical examples.

Reading from a File

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ifstream myfile;   // Create an object of ifstream
  myfile.open ("example.txt");  // Open a file
  if (myfile.is_open()) {   // If the file is open, read from it
    string line;
    while (getline (myfile, line)) {
      cout << line << '\n';  // Output the text from the file
    }
    myfile.close();   // Close the file
  }
  else cout << "Unable to open file"; 
  return 0;
}

In the above example, we're reading line by line from the file "example.txt" and printing each line.

Writing to a File

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;  // Create an object of ofstream
  myfile.open ("example.txt");  // Open a file
  if (myfile.is_open()) {   // If the file is open, write to it
    myfile << "Hello World!\n";  // Write to the file
    myfile.close();   // Close the file
  }
  else cout << "Unable to open file";
  return 0;
}

In this example, we're writing the string "Hello World!" to the file "example.txt".

Summary

In this tutorial, you've learned how to use ifstream and ofstream in C++ to read from and write to files. You can now perform basic file operations using streams in C++.

Next, you might want to learn more about handling errors during file operations, or explore more advanced file handling techniques.

Practice Exercises

  1. Write a program that reads a text file and counts the number of lines in it.
  2. Write a program that copies the contents of one file to another.
  3. Write a program that writes the numbers 1 to 10 on separate lines in a text file.

Solutions and explanations will be provided in the next tutorial. To practice further, you may want to try modifying these programs or creating your own.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help