c-plus-plus
  1. c-plus-plus-file-stream

C++ File & Stream

C++ provides a set of classes and functions that allow you to work with files and streams. Using these classes and functions, you can read from and write to files, as well as manipulate data stored in memory.

Syntax

To work with files in C++, you need to include the fstream header file and declare an instance of the fstream class.

#include <fstream>
using namespace std;

fstream file;

file.open("filename.txt", ios::in);  // for reading from a file
file.open("filename.txt", ios::out); // for writing to a file
file.open("filename.txt", ios::app); // for appending to a file

Example

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

int main() {
    fstream file;
    file.open("data.txt", ios::out);

    if (file.is_open()) {
        file << "Hello, C++!\n";
        file.close();
    }
    else {
        cout << "Unable to open file!\n";
        return 1;
    }

    file.open("data.txt", ios::in);

    if (file.is_open()) {
        string line;
        while (getline(file, line)) {
            cout << line << endl;
        }
        file.close();
    }
    else {
        cout << "Unable to open file!\n";
        return 1;
    }

    return 0;
}

Output

Hello, C++!

Explanation

In the above example, we create a file named data.txt and write the string "Hello, C++!" to it. We then close the file and open it again for reading. We read each line of the file and print it to the console.

Use

Files and streams are used when you need to store or retrieve data from a file. They are commonly used to read and write configuration files, input and output data, logs, and other types of data.

Important Points

  • You need to include the fstream header file to work with files in C++.
  • The fstream class allows you to open files for input, output, and appending.
  • is_open() method can be used to check if a file has been opened successfully.
  • Use the << operator to write data to a file and the getline() function to read data from a file.

Summary

In summary, working with files and streams is an important aspect of programming in C++. The fstream class allows you to easily read from and write to files. You can use this functionality to store or retrieve data in various types of applications.

Published on: