Skip to main content

How to open a file in C++

Short answer

A file is opened by creating an ifstream/ofstream/fstream object with the constructor (e.g., ofstreamfout('data.txt');) or by calling open(filename, mode). Modes include ios::in, out, app, binary, trunc, ate, combined with |.

How can a file be opened in C++? Explain with suitable example and syntax.

A file is opened in C++ by creating a file stream object (ifstream for input, ofstream for output, fstream for both) from <fstream> and linking it with a file. There are two ways.

1. Using the constructor

ofstream fout("data.txt");        // opens for writing
ifstream fin("data.txt");         // opens for reading

2. Using the open() member function

Syntax: stream_object.open("filename", mode);

#include <fstream>
#include <iostream>
using namespace std;
int main() {
    ofstream fout;
    fout.open("student.txt", ios::out | ios::app);   // append mode
    if (!fout) {
        cout << "File cannot be opened";
        return 1;
    }
    fout << "Ram 20" << endl;
    fout.close();
    return 0;
}

File modes

ModeMeaning
ios::inRead
ios::outWrite (truncates existing file)
ios::appAppend at end
ios::ateGo to end on opening
ios::binaryBinary mode
ios::truncDelete old contents
ios::nocreate / ios::noreplaceFail if file does not / does exist (old compilers)

Modes can be combined with |. ifstream uses ios::in and ofstream uses ios::out by default.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →