C++ File Input/Output Library - <fstream>

In C++, <fstream>is a class in the standard library for file input/output operations. It provides a convenient way to read and write files.

fstreamYesiostreampart of the library, supporting the reading and writing of text and binary files.

fstreamThe class isiostreamA class in the library that inherits fromistreamandostreamclass, which means it can be used for both input and output.

Syntax

fstreamThe basic syntax is as follows:

#include <fstream>

int main() {
    std::fstream file; // Create fstream object
    file.open("filename", mode); // Open file
    // Perform file operations
    file.close(); // Close file
    return 0;
}

wherefilenameis the name of the file,modeis the mode for opening files, common modes include:

  • std::ios::in: Opens the file in input mode.
  • std::ios::out: Opens the file in output mode.
  • std::ios::app: Opens the file in append mode.
  • std::ios::ate: Opens the file and positions at the end of the file.
  • std::ios::trunc: open the file and truncate it, i.e., clear the file content.

Example

Write to a text file:

Example

#include <fstream>
#include <iostream>

int main() {
    std::fstream file;
    file.open("example.txt", std::ios::out); // Open file in output mode

    if (!file) {
        std::cerr << "Unable to open file!" << std::endl;
        return 1; // Failed to open file
    }

    file << "Hello, World!" << std::endl; // Write text
    file.close(); // Close file

    return 0;
}

Create a file named in the current directoryexample.txtfile, the file content is:

Hello, World!

Read a text file

Example

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

int main() {
    std::fstream file;
    file.open("example.txt", std::ios::in); // Open file in input mode

    if (!file) {
        std::cerr << "Unable to open file!" << std::endl;
        return 1; // Failed to open file
    }

    std::string line;
    while (getline(file, line)) { // Read line by line
        std::cout << line << std::endl;
    }

    file.close(); // Close file

    return 0;
}

ifexample.txtThe file contains the following content:

Hello, World!
This is a test file.

then the program will output:

Hello, World!
This is a test file.

Append to a file:

Example

#include <fstream>
#include <iostream>

int main() {
    std::fstream file;
    file.open("example.txt", std::ios::app); // Open file in append mode

    if (!file) {
        std::cerr << "Unable to open file!" << std::endl;
        return 1; // Failed to open file
    }

    file << "Appending this line to the file." << std::endl; // Append text
    file.close(); // Close file

    return 0;
}

example.txtThe file originally contained the following content:

Hello, World!
This is a test file.

After executing the above program, the file content will become:

Hello, World!
This is a test file.
Appending this line to the file.
other extensions