File opening modes(r versus r+)
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:
- r
- r+
- 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;
fp = fopen ( "INPUT.txt" , "r+" );
while (1) {
ch = fgetc (fp);
if (ch == EOF)
break ;
printf ( "%c" , ch);
}
fclose (fp);
}
|
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;
fp = fopen ( "INPUT.txt" , "r+" );
while (1) {
ch = fgetc (fp);
if (ch == EOF)
break ;
printf ( "%c" , ch);
}
fprintf (fp, " online reference." );
fclose (fp);
fp = fopen ( "INPUT.txt" , "r+" );
while (1) {
ch = fgetc (fp);
if (ch == EOF)
break ;
printf ( "%c" , ch);
}
fclose (fp);
}
|
Output:
geeksforgeeks online reference
Last Updated :
14 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...