C++ Program to Make a File Read-Only
Here, we will build C++ Program to Make a File Read-Only using 2 approaches i.e.
- Using ifstream
- Using fstream
C++ programming language offers a library called fstream consisting of different kinds of classes to handle the files while working on them. The classes present in fstream are ofstream, ifstream, fstream.
1. Using “ifstream”
The output of the below code consists of data present in the specified “Geeks for Geeks.txt” file.
ifstream class is used to read the file and doesn’t support writing data into the file. i.e. making files available to read-only. The created input stream “ifstream in” specifies the file to be opened in reading mode.
C++
// C++ program to make the file // in read-only mode using ifstream #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
2. Using “fstream”
The fstream class is used to read the file and also enables writing data into the opened file.
Here in the below code, we opened a file in read mode by specifying “ios::in“ in the open method and displayed the data present in the file on the successful opening of a file.
C++
// C++ program to make the file // in read-only mode using fstream #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
Please Login to comment...