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

77 / 87 topics
76<iostream> Reference77<fstream> Reference78<cmath> Reference79<string> Reference80<cstring> Reference81<ctime> Reference82<vector> Reference83<algorithm> Reference
Tutorials/C++ Programming/<fstream> Reference
⚡C++ Programming

<fstream> Reference

Updated 2026-04-20
3 min read

Introduction

The <fstream> header in C++ is part of the Standard Library and provides facilities for file input and output operations. It includes classes that allow you to read from and write to files, as well as manipulate their contents. This tutorial will cover the essential aspects of using <fstream>, including opening and closing files, reading from and writing to them, handling errors, and best practices.

Overview of <fstream>

The <fstream> header defines several classes that are used for file operations:

  • ifstream: Used for input operations on files.
  • ofstream: Used for output operations on files.
  • fstream: Used for both input and output operations on files.

These classes inherit from the istream and ostream classes, which provide the core functionality for input and output operations in C++.

Opening Files

To perform file operations, you need to create an instance of one of the file stream classes (ifstream, ofstream, or fstream) and open a file using the open() method. The open() method takes two parameters: the name of the file and the mode in which the file should be opened.

Modes

The following modes can be used when opening files:

  • ios::in: Open for input operations.
  • ios::out: Open for output operations.
  • ios::app: Append to end of file on each write operation.
  • ios::ate: Set the initial position at the end of the file.
  • ios::trunc: If the file is opened for output operations, any existing contents are discarded.
  • ios::binary: Open in binary mode.

Example

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile;
    outFile.open("example.txt", std::ios::out);

    if (!outFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outFile << "Hello, World!" << std::endl;
    outFile.close();

    return 0;
}

In this example, an ofstream object is created and the file "example.txt" is opened in write mode. If the file cannot be opened, an error message is printed to the standard error stream.

Reading from Files

To read from a file, you can use an ifstream object. The most common way to read data from a file is using the extraction operator (>>) or the getline() method.

Using Extraction Operator

#include <fstream>
#include <iostream>

int main() {
    std::ifstream inFile;
    inFile.open("example.txt", std::ios::in);

    if (!inFile.is_open()) {
        std::cerr << "Failed to open file for reading." << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(inFile, line)) {
        std::cout << line << std::endl;
    }

    inFile.close();

    return 0;
}

In this example, an ifstream object is created and the file "example.txt" is opened in read mode. The contents of the file are read line by line using the getline() method.

Writing to Files

To write to a file, you can use an ofstream object. Data can be written to a file using the insertion operator (<<) or other methods like put() and write().

Example

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outFile;
    outFile.open("example.txt", std::ios::out | std::ios::app);

    if (!outFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outFile << "Appending new line." << std::endl;
    outFile.close();

    return 0;
}

In this example, an ofstream object is created and the file "example.txt" is opened in append mode. The string "Appending new line." is appended to the end of the file.

Error Handling

It's important to handle errors when performing file operations. You can check if a file was successfully opened using the is_open() method. Additionally, you can use the fail(), bad(), and eof() methods to check for different types of errors.

Example

#include <fstream>
#include <iostream>

int main() {
    std::ifstream inFile;
    inFile.open("nonexistent.txt", std::ios::in);

    if (!inFile.is_open()) {
        std::cerr << "Failed to open file for reading." << std::endl;
        return 1;
    }

    if (inFile.fail()) {
        std::cerr << "Error occurred while reading from the file." << std::endl;
    } else if (inFile.bad()) {
        std::cerr << "Bad error occurred while reading from the file." << std::endl;
    } else if (inFile.eof()) {
        std::cout << "End of file reached." << std::endl;
    }

    inFile.close();

    return 0;
}

In this example, an ifstream object is created and an attempt is made to open a non-existent file. The different error states are checked using the fail(), bad(), and eof() methods.

Best Practices

  1. Always Check if File is Open: Before performing any operations on a file, always check if it was successfully opened.
  2. Close Files Properly: Always close files after you're done with them to free up resources.
  3. Use RAII (Resource Acquisition Is Initialization): Consider using std::ifstream and std::ofstream as local variables in functions to ensure they are automatically closed when the function exits.
  4. Handle Errors Gracefully: Implement error handling mechanisms to manage different types of errors that may occur during file operations.

Conclusion

The <fstream> header provides a powerful set of tools for performing file input and output operations in C++. By understanding how to open, read from, write to, and handle errors with files, you can effectively manage data persistence in your applications. Always follow best practices to ensure robust and error-free file handling.

Additional Resources

  • C++ Standard Library Documentation
  • Effective Modern C++ by Scott Meyers

This tutorial should provide a comprehensive understanding of the <fstream> header and its usage in C++.


Previous<iostream> ReferenceNext <cmath> Reference

Recommended Gear

<iostream> Reference<cmath> Reference