Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

File opening modes(r versus r+)

  • Last Updated : 14 Aug, 2019

A file has to be opened before the beginning of reading and writing operations. Opening a file creates a link between the operating system and the file function.

Syntax for opening a file:

We provide nothing but the best curated videos and practice problems for our students. Check out the C Foundation Course and master the C language from basic to advanced level. Wait no more, start learning today!
  FILE *fp;
  fp = fopen( " filename with extension ", " mode " );

Opening of file in detail:
FILE: structure defined in stdio.h header file. FILE structure provides us the necessary information about a FILE.
fp: file pointer which contains the address of the structure FILE.
fopen(): this function will open file with name “filename” in specified “mode”.

Different reading modes:



  1. r
  2. r+
  3. for binary files: rb, rb+, r+b

Difference:

r moder+ mode
PurposeOpens an existing text file for reading purpose.Opens a text file for both reading and writing.
fopen Returns if FILE doesn’t existsNULLCreate New File
fopen returns if FILE existReturns a pointer to the FILE object.New data is written at the start of existing data
file pointer positionat the first char of the fileat the first char of the file

C program for opening file in r mode:




#include <stdio.h>
  
void main()
{
    FILE* fp;
    char ch;
    // Open file in Read mode
    fp = fopen("INPUT.txt", "r+");
  
    // data in file: geeksforgeeks
  
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fclose(fp); // Close File after Reading
}

Output:

geeksforgeeks

Note: File opened should be closed in the program after processing.

C program for opening file in r+ mode:




#include <stdio.h>
  
void main()
{
    FILE* fp;
    char ch;
    // Open file in Read mode
    fp = fopen("INPUT.txt", "r+");
  
    // content of the file:geeksforgeeks
  
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fprintf(fp, " online reference.");
  
    fclose(fp); // Close File after Reading
  
    // content of the file: geeksforgeeks online reference.
  
    fp = fopen("INPUT.txt", "r+"); // Open file in r + mode
    while (1) {
        ch = fgetc(fp); // Read a Character
        if (ch == EOF) // Check for End of File
            break;
  
        printf("%c", ch);
    }
    fclose(fp);
}

Output:

geeksforgeeks online reference



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!