The Wayback Machine - https://web.archive.org/web/20241127042520/https://www.geeksforgeeks.org/cpp-program-to-make-a-file-read-only/
Open In App

C++ Program to Make a File Read-Only

Last Updated : 28 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Here, we will build C++ Program to Make a File Read-Only using 2 approaches i.e.

  1. Using ifstream
  2. 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


Previous Article
Next Article

Similar Reads

C++ Program to Read Content From One File and Write it Into Another File
Here, we will see how to read contents from one file and write it to another file using a C++ program. Let us consider two files file1.txt and file2.txt. We are going to read the content of file.txt and write it in file2.txt Contents of file1.txt: Welcome to GeeksForGeeks Approach: Create an input file stream object and open file.txt in it.Create a
2 min read
C++ program to read file word by word
Given a text file, extract words from it. In other words, read the content of file word by word. Example : Input: And in that dream, we were flying. Output: And in that dream, we were flying. Approach : 1) Open the file which contains string. For example, file named "file.txt" contains a string "geeks for geeks". 2) Create a filestream variable to
1 min read
C++ Program to Read and Print All Files From a Zip File
In this article, we will explore how to create a C++ program to read and print all files contained within a zip archive. What are zip files? Zip files are a popular way to compress and store multiple files in a single container. They use an algorithm to decrease the size of the data they store. They also contain information about file type, name, s
3 min read
Read a record from a File in C++ using seekg() and tellg()
Given that a binary file "student.data" is already loaded in the memory of the computer with the record of 100 students, the task is to read the Kth record and perform some operations.seekg() is a function in the iostream library (part of the standard library) that allows you to seek to an arbitrary position in a file. It is used in file handling t
2 min read
How to Read and Parse Json File with RapidJson?
RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL. Here is an example o
5 min read
RapidJSON - File Read/Write in C++
RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data. It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes support for parsing and generating JSON in a strea
6 min read
Implement your own tail (Read last n lines of a huge file)
Given a huge file having dynamic data, write a program to read last n lines from the file at any point without reading the entire file. The problem is similar to tail command in linux which displays the last few lines of a file. It is mostly used for viewing log file updates as these updates are appended to the log files. Source : Microsoft Intervi
4 min read
lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”. lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms. Function Definition off_t lseek(int fild
2 min read
Read/Write Class Objects from/to File in C++
Given a file "Input.txt" in which every line has values same as instance variables of a class. Read the values into the class's object and do necessary operations.Theory : The data transfer is usually done using '>>' and <<' operators. But if you have a class with 4 data members and want to write all 4 data members from its object direc
3 min read
How to Read a File Line by Line in C++?
In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we'll learn how to read a file line by line in C++. Read a File Line by Line in C++We can use the std::getline() function to read the input line by line from a particular stream. We can redirect the
2 min read
How to Read a File Using ifstream in C++?
In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstream class in C++. Read File Using ifstream in C++To
2 min read
How to Read Whole ASCII File Into C++ std::string?
An ASCII file is a text file that has a standardized format so that information can be recognized and read easily by any platform or operating system. In C++, we represent the textual data as std::string objects. In this article, we will learn how to read a whole ASCII File into std::string in C++. Read Whole ASCII File into C++ std::stringTo read
2 min read
How to Read a File Character by Character in C++?
In C++, file handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk). In this article, we will learn how to read a file character by character in C++. Example: Input: "Geeks for Geeks"Output: G e e k s f o r G e e k sRead Text from a File Character by Character in C++To rea
2 min read
How to Initialize Array With Values Read from a Text File in C++?
In C++, arrays store a fixed-size collection of elements of the same type. We can initialize these elements with any valid value. In this article, we will learn to initialize a C++ array with values read from a text file. Example: Input:Text File = “array.txt” // contains 1 2 3 4 5Output:// Read the values from the file and initialize the array Arr
2 min read
How to Read Data from a CSV File to a 2D Array in C++?
A comma-separated value file also known as a CSV file is a file format generally used to store tabular data in plain text format separated by commas. In this article, we will learn how we can read data from a CSV file and store it in a 2D array in C++. Example: Input: CSV File = “data.csv” //contains: 1, Student1, C++ 2, Student2, Java 3, Student3,
3 min read
How to Read File into String in C++?
In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to create an input file stream for reading from the
2 min read
How to Read Binary Search Tree from File in C++?
A binary search tree is a hierarchical data structure in which for every node in the tree, the value of all nodes in the left subtree is less than the node's value and the value of all nodes in the right subtree is greater than the node's value. This property of the binary search tree makes it efficient for searching, insertion, and deletion operat
4 min read
How to Read From a File in C++?
Reading from a file means retrieving the data stored inside a file as input in the program. In this article, we will learn how to read data from a file in C++. Table of Content Read From a Text FileRead From a Binary FileRead From a File in C++ - FAQsThere are two types of files: text files and binary files and the method of reading data from these
4 min read
C++ Program to Copy One File into Another File
To copy the text/contents of one file to another file, we should know the basics of reading and writing a text file in C++. To copy the file using C++, we read the contents of the source file and write it into the destination file. Steps to copy one file to another in C++: Create objects of ifstream and ofstream classes.Check if they are connected
2 min read
C++ Program to Copy the Contents of One File Into Another File
Here, we will see how to develop a C++ program to copy the contents of one file into another file. Given a text file, extract contents from it and copy the contents into another new file. After this, display the contents of the new file. Approach:Open the first file which contains data. For example, a file named "file1.txt" contains three strings o
2 min read
How to make a C++ class whose objects can only be dynamically allocated?
The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class 'Test' with following rules. C/C++ Code Test t1; // Should generate compiler error Test *t3 = new Test; // Should work fine The idea is to create a private destructor in the class. When we make a private destructor, the
2 min read
C++ Program to Read Screen Pixels
Obtaining the color information about the screen pixels is a common operation performed by automation software, which relies on activity on the screen. The process is trivial, and such functionality is incorporated into programming languages with the help of Image/Window reading libraries. This article will teach you how to read screen pixels in C+
3 min read
How to create Binary File from the existing Text File?
In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let's have an introduction of what are text files and binary files. Text files: Text files store data in human-readable form and sequentially. Binary files: Binary files store data in the form of bits/groups of bits (bytes) in sequ
7 min read
Difference Between C++ Text File and Binary File
A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters. Text files are organized around lines, each of which ends with a newline character ('\n'). The source code files are themselves text files. A binary file is the one in which data is stored in the file in the same w
4 min read
Recursive program to print all numbers less than N which consist of digits 1 or 3 only
Given an integer N, the task is to print all the numbers ? N which have their digits as only 1 or 3.Examples: Input: N = 10 Output: 3 1 Input: N = 20 Output: 13 11 3 1 Approach: First, check if the number is greater than 0. If yes then proceed further, else program is terminated.Check for the presence of digits 1 or 3 at each place of the number.If
7 min read
C++ Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. Examples :   Input: arr[] = {1, 20, 2, 10} Output: 72 We can get 72 by rotating array twice. {2, 10, 1, 20} 20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9} Outp
4 min read
C++ Program to Check String is Containing Only Digits
Prerequisite: Strings in C++ The string is the collection of characters or text in a string variable, surrounded by double quotes. One question arises How can we check string contains only digits in C++? So, to solve this query we can use the methods mentioned in the article given below: Example: "125" -> True "1h25" -> False "012" -> True
3 min read
How to Read and Print an Integer value in C++
The given task is to take an integer as input from the user and print that integer in C++ language. In this article, we will learn how to read and print an integer value. In the below program, the syntax and procedures to take the integer as input from the user is shown in C++ language. Standard Input StreamThe user enters an integer value when ask
2 min read
Read a string after reading an integer
In this article, we will discuss how to read a string after reading an integer. Program 1: Below is the program that inputs a string with spaces just after taken an input of an integer: C/C++ Code // C++ program that inputs a string // with spaces just after taken an // input of an integer #include <iostream> #include <string> using nam
2 min read
How to Read Input Until EOF in C++?
In C++, EOF stands for End Of File, and reading till EOF (end of file) means reading input until it reaches the end i.e. end of file. In this article, we will discuss how to read the input till the EOF in C++. Read File Till EOF in C++The getline() function can be used to read a line in C++. We can use this function to read the entire file until EO
2 min read
Practice Tags :
three90RightbarBannerImg