C++ Program to Make a File Read-Only
Last Updated :
28 Jul, 2022
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++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream 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++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream readFile;
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;
}
}
readFile.close();
return 0;
}
|
Output:
Geeks_for_Geeks
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...