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

Introduction to File Handling in C++

This tutorial will introduce you to the basics of file handling in C++. You'll learn how to open, read, write, and close files using the C++ standard library.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

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

1. Introduction

This tutorial aims to introduce you to the basics of file handling in C++. File handling is an essential part of programming that deals with creating, reading, writing, and closing files.

By the end of this tutorial, you will learn how to:
- Open a file
- Read from a file
- Write to a file
- Close a file

Prerequisites: A basic understanding of C++ programming language.


2. Step-by-Step Guide

Opening a File

In C++, we use the fstream library to work with files. The fstream library provides the fstream class to read and write to files.

To open a file, we use open function of fstream or ofstream or ifstream objects.

fstream myFile;
myFile.open("example.txt");

Reading from a File

To read from a file, we use the >> operator.

string lineData;
myFile >> lineData;

Writing to a File

To write to a file, we use the << operator.

myFile << "This is a new line of text";

Closing a File

After we are done with our operations on the file, we close the file by calling the close method of the fstream object.

myFile.close();

3. Code Examples

Example 1: Writing to a file

#include <fstream>

int main() {
    std::ofstream myFile;
    myFile.open("example.txt");

    if (myFile.is_open()) {
        myFile << "This is a new line of text\n";
    }

    myFile.close();

    return 0;
}

This C++ code opens a file named "example.txt", writes a line of text to it, and then closes the file.

Example 2: Reading from a file

#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::ifstream myFile;
    myFile.open("example.txt");

    if (myFile.is_open()) {
        std::string lineData;
        while (getline(myFile, lineData)) {
            std::cout << lineData << "\n";
        }
    }

    myFile.close();

    return 0;
}

This C++ code opens a file named "example.txt", reads line by line from it, prints each line to the console, and then closes the file.


4. Summary

In this tutorial, you learned the basics of file handling in C++. You learned how to open, read from, write to, and close files using the fstream library in C++.

For further learning, you can explore how to handle errors during file operations and how to work with binary files.


5. Practice Exercises

  1. Write a C++ program to write the numbers from 1 to 10 to a file.
  2. Write a C++ program to read the file created in the previous exercise and print the numbers to the console.
  3. Write a C++ program that asks the user for a number n and a string, then writes the string to a file n times.

Here are the solutions for the above exercises:

  1. Here is how you can write numbers from 1 to 10 to a file:
#include <fstream>

int main() {
    std::ofstream myFile;
    myFile.open("numbers.txt");

    if (myFile.is_open()) {
        for (int i = 1; i <= 10; i++) {
            myFile << i << "\n";
        }
    }

    myFile.close();

    return 0;
}
  1. Here is how you can read the numbers from the file:
#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::ifstream myFile;
    myFile.open("numbers.txt");

    if (myFile.is_open()) {
        std::string lineData;
        while (getline(myFile, lineData)) {
            std::cout << lineData << "\n";
        }
    }

    myFile.close();

    return 0;
}
  1. Here is how you can write a string to a file n times:
#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::ofstream myFile;
    myFile.open("repeatedString.txt");

    if (myFile.is_open()) {
        std::string myString;
        int n;
        std::cout << "Enter a string: ";
        getline(std::cin, myString);
        std::cout << "Enter a number: ";
        std::cin >> n;
        for (int i = 0; i < n; i++) {
            myFile << myString << "\n";
        }
    }

    myFile.close();

    return 0;
}

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

Backlink Checker

Analyze and validate backlinks.

Use tool

Word Counter

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

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

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