C++ Program to Make a File Read-Only

Last Updated : 2 Sep, 2026

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.

C++
#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_Geeks

Explanation

  • 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.

C++
#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_Geeks

Explanation

  • 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

Featureifstreamfstream with ios::in
PurposeReading filesReading and writing files
Read operationSupportedSupported
Write operationNot supported through the streamNot enabled when opened with ios::in
Mode requiredInput mode by defaultios::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.

Comment