Labs ICT
โญ Pro Login

File Handling

1 min read | C++ Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

File Handling

C++ provides the fstream library for file input/output. The main classes are ifstream (input), ofstream (output), and fstream (both).

Opening and Creating Files

Use the constructor or open() method. Specify the file name and mode. Common modes: ios::out (write), ios::in (read), ios::app (append).

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

int main() {
  ofstream file("example.txt");
  if (file.is_open()) {
    file << "Hello, file!\n";
    file << "C++ file handling is easy.\n";
    file.close();
    cout << "File created and written.\n";
  }
  return 0;
}

๐Ÿงช Quick Quiz

Which class is used to read from files in C++?