C++ provides file-stream classes to work with files and control how they are opened for reading and writing. A file can be opened in read-only mode so that the program can read its contents without opening it for writing.
- ifstream is specifically designed for reading files.
- fstream supports both reading and writing data to files.
Approaches to Open a File in Read-Only Mode
There are two common approaches to open a file in read-only mode in C++:
1. Using ifstream
The ifstream class is used specifically for input operations and is suitable when the program only needs to read data from a file.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
// creating an input stream
ifstream in;
// opening a file in read mode using in
in.open("Geeks for Geeks.txt");
if (!in)
cout << "No file found";
else {
char c;
while (1) {
in >> c;
if (in.eof())
break;
cout << c;
}
}
in.close();
return 0;
}
Output
Geeks_for_GeeksExplanation
- ifstream in creates an input stream, and in.open() opens the file in read mode.
- if (!in) checks whether the file was opened successfully.
- The while loop reads and prints the file contents character by character.
- in.close() closes the file after reading.
2. Using fstream
The fstream class supports both input and output operations. To open a file only for reading, pass ios::in while opening the file.
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream readFile;
// opening a file in read mode
readFile.open("Geeks for Geeks.txt", ios::in);
if (!readFile)
cout << "No such file exist";
else {
char c;
while (1) {
readFile >> c;
if (readFile.eof())
break;
cout << c;
}
}
// closing the file
readFile.close();
return 0;
}
Output
Geeks_for_GeeksExplanation
- fstream readFile creates a file stream, and open() with ios::in opens the file in read mode.
- if (!readFile) checks whether the file was opened successfully.
- The while loop reads and displays the file contents character by character.
- readFile.close() closes the file after reading.
Difference Between ifstream and fstream
| Feature | ifstream | fstream with ios::in |
|---|---|---|
| Purpose | Reading files | Reading and writing files |
| Read operation | Supported | Supported |
| Write operation | Not supported through the stream | Not enabled when opened with ios::in |
| Mode required | Input mode by default | ios::in |
Note: Opening a file in read-only mode in C++ does not necessarily change the file's operating-system permissions. It only controls how the file is accessed through that particular stream.