- 2074 Chaitra · 2 marks
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
| Mode | Meaning |
|---|---|
ios::in | Read |
ios::out | Write (truncates existing file) |
ios::app | Append at end |
ios::ate | Go to end on opening |
ios::binary | Binary mode |
ios::trunc | Delete old contents |
ios::nocreate / ios::noreplace | Fail 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)
Related questions
- Engineer opens confidential salary file · Engineering Professional Practice, chapter 7
- Line opened: stability and rotor swing · Power System Analysis II, chapter 6
- INVENTORY file of items · Computer Programming, chapter 10