File opening modes(r versus r+) in C++

C++Server Side ProgrammingProgramming

File handling in programming languages is very important for the interaction of programming with the memory for accessing files and fetching data in it.

Using a program, you can read data from a file as well as write data to the file and do a lot more functions.

Here, we will see reading of data from a file.

In programming, before performing any operation you need to open the file. And there are multiple modes to open a file in the programming language. The access to the file is based on the mode it is opened with.

Here we will learn about the difference between two modes of opening file for reading files, these are r and r+.

Both are used for reading files in the program.

Syntax for opening a file : 

          FILE *fp;

          fp = fopen( “filename.fileextension” , “mode” )

r mode for opening a file: 

The r mode for opening file, opens files for reading only. If the file does not exist NULL character is returned.

Program to illustrate the opening of file:

Example

#include <stdio.h>
#include <iostream>
using namespace std;

int main() {
   
   FILE* readFile;
   char ch;
   readFile = fopen("file.txt", "r");
   while (1) {
      ch = fgetc(readFile);
      if (ch == EOF)
         break;
      cout<<ch;
   }
   fclose(readFile);
}

Output −

Tutorials Point

r+ mode for opening a file:

The r+ mode for opening a file is similar to r mode but has some added features. It opens the file in both read and write mode. If the file does not exist with w+, the program creates new files to work on it.

Program to illustrate the opening of file in r+ mode:

Example

#include <stdio.h>
#include <iostream>
using namespace std;

int main() {
   
   FILE* readFile;
   char ch;
   readFile = fopen("file.txt", "r+");
   while (1) {
      ch = fgetc(readFile);
      if (ch == EOF)
         break;
      cout<<ch;
   }
   fclose(readFile);
}

Output −

Tutorials Point
raja
Published on 22-Jan-2021 13:44:35
Advertisements