The Wayback Machine - https://web.archive.org/web/20241129131841/https://www.geeksforgeeks.org/file-opening-modesr-versus-r/
Open In App

File opening modes(r versus r+)

Last Updated : 14 Aug, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  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 mode r+ mode
Purpose Opens an existing text file for reading purpose. Opens a text file for both reading and writing.
fopen Returns if FILE doesn’t exists NULL Create New File
fopen returns if FILE exist Returns a pointer to the FILE object. New data is written at the start of existing data
file pointer position at the first char of the file at 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


Previous Article
Next Article

Similar Reads

C program to check whether the file is JPEG file or not
Write a C program which inputs a file as a command-line arguments and detects whether the file is JPEG(Joint Photographic Experts Group) or not. Approach: We will give an image as a command line argument while executing the code. Read the first three bytes of the given image(file). After reading the file bytes, compare it with the condition for JPE
2 min read
C | File Handling | Question 1
Which of the following true about FILE *fp (A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type (C) FILE is a stream (D) FILE is a buffered stream Answer: (B) Explanation: fp is a pointer of FILE type and FILE is a structure that store followin
1 min read
C | File Handling | Question 2
When fopen() is not able to open a file, it returns (A) EOF (B) NULL (C) Runtime Error (D) Compiler Dependent Answer: (B) Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.Quiz of this Question
1 min read
C | File Handling | Question 3
getc() returns EOF when (A) End of files is reached (B) When getc() fails to read a character (C) Both of the above (D) None of the above Answer: (C) Explanation: See EOF, getc() and feof() in CQuiz of this Question
1 min read
C | File Handling | Question 4
In fopen(), the open mode "wx" is sometimes preferred "w" because. 1) Use of wx is more efficient. 2) If w is used, old contents of file are erased and a new empty file is created. When wx is used, fopen() returns NULL if file already exists. (A) Only 1 (B) Only 2 (C) Both 1 and 2 (D) Neither 1 nor 2 Answer: (B) Explanation: See https://www.geeksfo
1 min read
C | File Handling | Question 5
fseek() should be preferred over rewind() mainly because (A) rewind() doesn't work for empty files (B) rewind() may fail for large files (C) In rewind, there is no way to check if the operations completed successfully (D) All of the above Answer: (C) Explanation: Please see fseek() vs rewind() in CQuiz of this Question
1 min read
C Program For Lower Case to Uppercase and Vice-Versa in a File
Given a text file(gfg.txt), our task is to convert all the lowercase characters of the file into uppercase. ExamplesInput: (content inside file gfg.txt) An extensive classroom programme by GeeksforGeeks to build and enhance Data Structures and Algorithm concepts Output: (content inside file gfg.txt) AN EXTENSIVE CLASSROOM PROGRAMME BY GEEKSFORGEEKS
4 min read
C program for file Transfer using UDP
Data can be transferred between two computers using Socket programming in C. Similarly, files can easily be sent using UDP protocol and a simple client/server. Security: Handled by encryption. Protocol : UDP Encryption: XOR encryption Algorithm : 1. The server starts and waits for filename. 2. The client sends a filename. 3. The server receives fil
4 min read
C Program to find size of a File
Given a text file, find its size in bytes. Examples: Input : file_name = "a.txt" Let "a.txt" contains "geeks" Output : 6 Bytes There are 5 bytes for 5 characters then an extra byte for end of file. Input : file_name = "a.txt" Let "a.txt" contains "geeks for geeks" Output : 16 Bytes The idea is to use fseek() in C and ftell in C. Using fseek(), we m
1 min read
Bank account system in C using File handling
This article focuses on how to create a bank account system using C language and File handling in C. Approach:Let's discuss the approach in detail, covering all the functions and their explanation in detail- Create a Menu in the main function and create different functions for the Menu, which will be called using switch case statements. There are f
12 min read
Sorting integer data from file and calculate execution time
Prerequisite: Selection Sort In this article, we are going to apply selection sort algorithm, in which the source of input is A FILE CONTAINING 10000 INTEGERS and output will be the total time taken to sort. Important functions to be used: rand(): Used to generate random numbers. fopen(): Used to open file . fscanf(): Used to scan data from file .
3 min read
Lex Program to print the total characters, white spaces, tabs in the given input file
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The commands for executing the lex program are: lex abc.l (abc is the file name) cc lex.yy.c -lfl ./a.out Let’s see Lex program to print the total charact
1 min read
Lex code to replace a word with another word in a file
Given a text file as input, the task is to replace a given word with another word in the file. Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite:
2 min read
Lex program to search a word in a file
Problem: Write a Lex program to search a word in a file. Explanation: FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C progr
2 min read
Basics of File Handling in C#
Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operation which is mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for
3 min read
<complex.h> header file in C with Examples
Most of the C Programs deals with complex number operations and manipulations by using complex.h header file. This header file was added in C99 Standard. C++ standard library has a header, which implements complex numbers as a template class, complex<T>, which is different from <complex.h> in C. Macros associated with <complex.h>
5 min read
C program to find and replace a word in a File by another given word
Pre-requisite: File Handling in CGiven a file containing some text, and two strings wordToBeFind and wordToBeReplacedWith, the task is to find all occurrences of the given word 'wordToBeFind' in the file and replace them with the given word ‘wordToBeReplacedWith’. Examples: Input : File = "xxforxx xx for xx", wordToBeFind = "xx", wordToBeReplacedWi
3 min read
C program to reverse the content of the file and print it
Given a text file in a directory, the task is to print the file content backward i.e., the last line should get printed first, 2nd last line should be printed second, and so on.Examples: Input: file1.txt has: Welcome to GeeksforGeeks Output: GeeksforGeeks to WelcomeGeeksforGeeks Input: file1.txt has: This is line one This is line two This is line t
3 min read
C program to print odd line contents of a File followed by even line content
Pre-requisite: Basics of File Handling in C Given a text file in a directory, the task is to print all the odd line content of the file first then print all the even line content. Examples: Input: file1.txt: Welcome to GeeksforGeeks Output: Odd line contents: Welcome GeeksforGeeks Even line contents: to Input: file1.txt: 1. This is Line1. 2. This i
2 min read
C program to append content of one text file to another
Pre-requisite: File Handling in C Given the source and destination text files, the task is to append the content from source file to destination file and then display the content of the destination file.Examples: Input: file1.text This is line one in file1 Hello World. file2.text This is line one in file2 Programming is fun. Output: This is line on
2 min read
Employee Record System in C using File Handling
Employee Record System is software built to handle the primary housekeeping functions of a company. ERS helps companies keep track of all the employees and their records. It is used to manage the company using a computerized system. This software built to handle the records of employees of any company. It will help companies to keep track of all th
5 min read
C program to read a range of bytes from file and print it to console
Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console. Functions Used: fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For closing a file. Approach: Initialize a file pointer,
2 min read
How to write in a file using fputs() in C
fputs() is a function declared in stdio.h header file. It is used to write the contents of the file. The function takes 2 arguments. The first argument is a pointer to the string which is to be written and the second argument is the pointer of the file where the string is to be written. It returns 1 if the write operation was successful, otherwise,
2 min read
C Program to Read and Print All Files From a Zip File
To understand how to write a C program for reading and printing zip files, it's important to know what exactly a zip file is. At its core, a zip file contains one or more files compressed using specific compression algorithms.Including the compressed data of the files, the zip file contains meta and header information about all files inside the zip
6 min read
time.h header file in C with Examples
The time.h header file contains definitions of functions to get and manipulate date and time information. It describes three time-related data types. clock_t: clock_t represents the date as an integer which is a part of the calendar time. time_t: time_t represents the clock time as an integer which is a part of the calendar time. struct tm: struct
4 min read
How to write your own header file in C?
As we all know that files with .h extension are called header files in C. These header files generally contain function declarations which we can be used in our main C program, like for e.g. there is need to include stdio.h in our C program to use function printf() in the program. So the question arises, is it possible to create your own header fil
4 min read
Error Handling During File Operations in C
It is quite common that errors may occur while reading data from a file or writing data to a file in C. For example, an error may arise due to the following: When trying to read a file beyond the indicator.When trying to read a file that does not exist.When trying to use a file that has not been opened.When trying to use a file in an inappropriate
5 min read
Sort Numbers from File Using Unix Pipes in C
In this article, we will write a straightforward C program that sorts numerical data from a file using pipes and forks.The sorting process is carried out using the sort command and the execlp function of UNIX. Working of the ProgramWe need to include the following header files to use the relevant functions:#include <stdio.h>#include <strin
3 min read
File I/O in Rust
File I/O in Rust enables us to read from and write to files on our computer. To write or read or write in a file, we need to import modules (like libraries in C++) that hold the necessary functions. This article focuses on discussing File I/O in Rust. Methods for File I/O Given below are some methods and their syntax for various file I/O operations
7 min read
How to Read a Struct from a Binary File in C?
The structure in C allows the users to create user-defined data types that can be used to group data items of different types into a single unit. We can save this structure in a file using C file handling. In this article, we will learn how we can read a struct from a binary file in C. Read a Struct from a Binary File in CTo read a struct from a bi
2 min read
Article Tags :
three90RightbarBannerImg