Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

C++ File Handling: Mastering Open, Read, Write, and Close Operations

What is file handling in C++?

File handling lets you persist program data on storage devices. By directing program output to a file, you can perform further manipulation, analysis, or archival on that data.

A stream is an abstraction that represents a continuous source or destination of characters. C++ supplies a robust fstream library that offers classes and functions to work seamlessly with files.

In this tutorial you will learn:

The fstream Library

The fstream library supplies three core classes:

Below is a quick visual reference:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

To use these classes, include the fstream header and, if you wish to output to the console, iostream as well.

How to Open Files

Before any file operation, the file must be opened. Use ofstream for write‑only access, ifstream for read‑only, and fstream for both. Each class provides an open() member:

open(file_name, mode);
ValueDescription
ios::appAppend mode – writes are added to the file end.
ios::ateOpen and immediately seek to the end.
ios::inOpen for reading.
ios::outOpen for writing.
ios::truncTruncate an existing file to zero length.

Multiple flags can be combined using the bitwise OR operator (|).

Example 1: Creating a File

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    fstream my_file;
    my_file.open("my_file", ios::out);
    if (!my_file) {
        cout << "File not created!";
    }
    else {
        cout << "File created successfully!";
        my_file.close();
    }
    return 0;
}

Output:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Screenshot of the running program:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Code Walk‑through:

  1. Include iostream for console I/O.
  2. Include fstream for file streams.
  3. Use the std namespace for brevity.
  4. Instantiate a fstream object named my_file.
  5. Open the file in write mode (ios::out).
  6. Check for successful opening; otherwise report failure.
  7. On success, print confirmation and close the file.
  8. Return 0 to indicate normal termination.

How to Close Files

While C++ automatically flushes and closes streams at program exit, explicitly closing a file after its last operation is considered good practice.

The close() member is available on fstream, ofstream, and ifstream:

void close();

How to Write to Files

Write operations use the stream insertion operator (<<). Text to be stored must be quoted or streamed directly.

Example 2: Writing Text

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    fstream my_file;
    my_file.open("my_file.txt", ios::out);
    if (!my_file) {
        cout << "File not created!";
    }
    else {
        cout << "File created successfully!";
        my_file << "Guru99";
        my_file.close();
    }
    return 0;
}

Output:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Code screenshot:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Code Walk‑through:

  1. Include necessary headers.
  2. Create a fstream object.
  3. Open the target file in write mode.
  4. Validate the file stream.
  5. Insert the string "Guru99" into the file.
  6. Close the stream.
  7. Return 0.

How to Read from Files

Reading uses the stream extraction operator (>>) just like cin. The data is streamed into variables of appropriate types.

Example 3: Reading Characters

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    fstream my_file;
    my_file.open("my_file.txt", ios::in);
    if (!my_file) {
        cout << "No such file";
    }
    else {
        char ch;
        while (1) {
            my_file >> ch;
            if (my_file.eof())
                break;
            cout << ch;
        }
    }
    my_file.close();
    return 0;
}

Output:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Screenshot of the running code:

C++ File Handling: Mastering Open, Read, Write, and Close Operations

Code Walk‑through:

  1. Include iostream and fstream.
  2. Open the file for reading (ios::in).
  3. Check for existence; if absent, notify the user.
  4. Read characters one by one until EOF is reached.
  5. Print each character to the console.
  6. Close the stream.
  7. Return 0.

Summary


C Language

  1. C File Handling: Mastering I/O with fopen, fprintf, fread, and fseek
  2. Initializing FPGA Block RAM from Text Files Using VHDL’s TEXTIO Library
  3. Mastering C File I/O: Create, Open, Read, Write, and Close Files with Confidence
  4. Reading Files in Java with BufferedReader – A Practical Guide with Examples
  5. Master Python File Handling: Create, Read, Write, and Open Text Files with Ease
  6. How to Read and Write CSV Files in Python: A Comprehensive Guide
  7. Understanding C Header Files: Types, Usage, and Best Practices
  8. Mastering File I/O in C++: Reading and Writing with fstream
  9. Mastering C++ Exception Handling: A Comprehensive Guide
  10. Master C++ Signal Handling: Safe Interrupt Management and Clean Program Termination