Opening Modes in Standard I/O in C/C++ with Examples
Last Updated :
01 Feb, 2023
Pre-requisites: File Handling in C++
So far the operations using the C program are done on a prompt/terminal that is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are:
- Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”).
- Opening an existing file (fopen).
- Reading from file (fscanf or fgets).
- Writing to a file (fprintf or fputs).
- Moving to a specific location in a file (fseek, rewind).
- Closing a file (fclose).
The text in the brackets denotes the functions used for performing those operations.
Why files are needed?
- Data Preservation: Storing data in files helps to preserve data even if the program terminates.
- Easy Data Access: Accessing data becomes easy when there is a large amount of data and it is stored in the file, then this data can be accessed using the C commands.
- Portability: It becomes easier to move data from one computer to another without any changes.
Types of files
They are two types of files that everyone should be aware of-
- Text Files: Text files are the normal files that have an extension “.txt” in the file name. These can be simply created using editors like Notepad. Upon opening the files the text will be visible like simple plain text and the content can be easily edited or deleted. These are the lowest maintenance files, easy to read. But there are a few disadvantages of text files like they are the least secure files and take bigger storage space.
- Binary Files: Binary files are “.bin” extension files. Data in these files are stored in the binary form i.e. 0’s and 1’s. These files can hold a large amount of data and provide a higher level of security than text files but these files are not easily readable.
File Operations
There are four basic operations that can be performed on a file:
- Creating a new file.
- Opening an existing file.
- Reading from or writing information to the file.
- Closing the file.
Working with files
When working with the files, there is a need to declare a pointer of the type file. This file-type pointer is needed for communication between the file and the program.
File *fptr;
Opening a file
Opening a file is done using the fopen() function in the header file stdio.h.
Syntax:
fptr = fopen(“file_name”, “mode”);
Example:
fopen(“D:\\geeksforgeeks\\newprogramgfg.txt”, “w”); fopen(“D:\\geeksforgeeks\\oldprogramgfg.bin”, “rb”);
- Suppose the file newprogramgfg.txt doesn’t exist in the location D:\geeksforgeeks. The first function creates a new file named newprogramgfg.txt and opens it for writing as per the mode ‘w’. The writing mode allows you to create and edit (overwrite) the contents of the file.
- Suppose the second binary file oldprogramgfg.bin exists in the location D:\geeksforgeeks. The second function opens the existing file for reading in binary mode ‘rb’. The reading mode only allows one to read the file, one cannot write into the file.
File Opening modes in C:
Mode |
Meaning of Mode |
During Inexistence of file |
r |
Open for reading. |
If the file does not exist, fopen( ) returns NULL. |
rb |
Open for reading in binary mode. |
If the file does not exist, fopen( ) returns NULL. |
w |
Open for writing. |
If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
wb |
Open for writing in binary mode. |
If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
a |
Open for append. |
Data is added to the end of the file. If the file does not exist, it will be created. |
ab |
Open for append in binary mode. |
Data is added to the end of the file. If the file does not exist, it will be created. |
r+ |
Open for both reading and writing. |
If the file does not exist, fopen( ) returns NULL. |
rb+ |
Open for both reading and writing in binary mode. |
If the file does not exist, fopen( ) returns NULL. |
w+ |
Open for both reading and writing. |
If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
wb+ |
Open for both reading and writing in binary mode. |
If the file exists, its contents are overwritten. If the file does not exist, it will be created. |
a+ |
Open for both reading and appending. |
If the file does not exist, it will be created. |
ab+ |
Open for both reading and appending in binary mode. |
If the file does not exist, it will be created. |
Closing a file
The file should be closed after reading or writing. Closing a file is performed using the fclose() function.
Syntax:
fclose(fptr);
Here, fptr is the file type pointer associated with the file to be closed.
Reading and writing to a text file
For reading and writing to a text file, the functions fprintf() and fscanf() are used. They are the file versions of the printf() and scanf() functions. The only difference is that the fprintf() and fscanf() expect the pointer to the structure file.
Write to a text file:
Syntax:
FILE *filePointer; filePointer = fopen(“filename.txt”, “w”)
Below is the C program to write to a text file.
C
#include <stdio.h>
#include <string.h>
int main()
{
FILE * filePointer;
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer"
+ " Science Portal for Geeks" ;
filePointer = fopen ( "GfgTest.txt" , "w" );
if (filePointer == NULL) {
printf ( "GfgTest.txt file failed to open." );
}
else {
printf ( "The file is now opened.\n" );
if ( strlen (dataToBeWritten) > 0) {
fprintf (filePointer, dataToBeWritten);
fprintf (filePointer, "\n" );
}
fclose (filePointer);
printf ( "Data successfully written"
+ " in file GfgTest.txt\n" );
printf ( "The file is now closed." );
}
return 0;
}
|
Output:
Read from a file:
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.txt”, “r”);
Below is the C program to read text file.
C
#include <stdio.h>
#include <string.h>
int main()
{
FILE * filePointer;
char dataToBeRead[50];
filePointer = fopen ( "GfgTest.txt" , "r" );
if (filePointer == NULL) {
printf ( "GfgTest.txt file failed to open." );
}
else {
printf ( "The file is now opened.\n" );
while ( fgets (dataToBeRead, 50,
filePointer)
!= NULL) {
printf ( "%s" , dataToBeRead);
}
fclose (filePointer);
printf ( "Data successfully read"
+ " from file GfgTest.txt\n" );
printf ( "The file is now closed." );
}
return 0;
}
|
Output:
Reading and writing in binary file
Write a binary file:
Syntax:
FILE *filePointer; filePointer = fopen(“fileName.bin”, “wb”);
To write data to a binary file, fwrite() function is needed. This function takes four arguments:
- Address of data to be written in the disk.
- Size of data to be written on the disk.
- The number of such types of data.
- Pointer to the file where you want to write.
Syntax:
fwrite(addressData, sizeofData, numbersData, pointerToFile);
Below is the C program to implement the above approach:
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE * fptr;
if ((fptr = fopen ( "C:\\GfgTest.bin" ,
"wb" ))
== NULL) {
printf ( "Error! opening file" );
exit (1);
}
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite (&num, sizeof ( struct threeNum),
1, fptr);
}
printf ( "The file GfgTest.bin is"
+ " written successfully" );
fclose (fptr);
return 0;
}
|
Read from a binary file:
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.txt”, “rb”);
To read data from a binary file, fread(0 function is used. Similar to fwrite() function, this function also takes four arguments.
Syntax:
fread(addressData, sizeofData, numbersData, pointerToFile);
Below is the C program to implement the above approach:
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE * fptr;
if ((fptr = fopen ( "C:\\GfgTest.bin" ,
"rb" ))
== NULL) {
printf ( "Error! opening file" );
exit (1);
}
for (n = 1; n < 5; ++n) {
fread (&num, sizeof ( struct threeNum),
1, fptr);
printf ( "n1: %d\tn2: %d\tn3: %d" ,
num.n1, num.n2, num.n3);
printf ( "\n" );
}
fclose (fptr);
return 0;
}
|
Output:
Append content in text file
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.txt”, “a”);
Once file is opened in append mode, rest of the task is same as that to write content in a text file.
Below is the example to append a string to the file:
C
#include <stdio.h>
#include <string.h>
int main()
{
FILE * filePointer;
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics" ;
filePointer = fopen ( "GfgTest.txt" , "a" );
if (filePointer == NULL) {
printf ( "GfgTest.txt file failed to open." );
}
else {
printf ( "The file is now opened.\n" );
if ( strlen (dataToBeWritten) > 0) {
fprintf (filePointer, dataToBeWritten);
fprintf (filePointer, "\n" );
}
fclose (filePointer);
printf ( "Data successfully appended"
+ " in file GfgTest.txt\n" );
printf ( "The file is now closed." );
}
return 0;
}
|
Output:
Append content in binary file
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.bin”, “ab”);
Once file is opened in append mode, rest of the task is same as that to write content in a binary file.
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE * fptr;
if ((fptr = fopen ( "C:\\GfgTest.bin" ,
"ab" ))
== NULL) {
printf ( "Error! opening file" );
exit (1);
}
for (n = 1; n < 10; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite (&num, sizeof ( struct threeNum),
1, fptr);
}
printf ( "The file GfgTest.bin"
+ " is appended successfully" );
fclose (fptr);
return 0;
}
|
Output:
Opening file for both reading and writing
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.txt”, “r+”);
The file is opened using the mode “r+'” and the file is opened in both reading and writing mode.
C
#include <stdio.h>
#include <string.h>
int main()
{
FILE * filePointer;
char dataToBeWritten[100]
= "It is a platform for"
+ " learning language"
+ " tech related topics." ;
char dataToBeRead[50];
filePointer = fopen ( "GfgTest.txt" , "r+" );
if (filePointer == NULL) {
printf ( "GfgTest.txt file failed to open." );
}
else {
printf ( "The file is now opened.\n" );
while ( fgets (dataToBeRead, 50,
filePointer)
!= NULL) {
printf ( "%s" , dataToBeRead);
}
printf (
"\nData successfully read"
+ " from file GfgTest.txt" );
if ( strlen (dataToBeWritten) > 0) {
fprintf (filePointer, dataToBeWritten);
fprintf (filePointer, "\n" );
}
printf ( "\nData successfully"
+ " written to the file" );
fclose (filePointer);
printf ( "\nThe file is now closed." );
}
return 0;
}
|
Output:
Opening file for both reading and writing in binary mode
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.bin”, “rb+”);
C
#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE * fptr;
if ((fptr = fopen ( "C:\\GfgTest.bin" ,
"rb" ))
== NULL) {
printf ( "Error! opening file" );
exit (1);
}
for (n = 1; n < 5; ++n) {
fread (&num, sizeof ( struct threeNum),
1, fptr);
printf ( "n1: %d\tn2: %d\tn3: %d" ,
num.n1, num.n2, num.n3);
printf ( "\n" );
}
printf ( "Data successfully read from the file" );
for (n = 1; n < 7; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
fwrite (&num, sizeof ( struct threeNum),
1, fptr);
}
printf ( "The file GfgTest.bin"
+ " is written successfully" );
fclose (fptr);
return 0;
}
|
Output:
Opening file for both reading and writing in text mode
In this mode, the file is opened for both reading and writing in text mode. If the file exists, then the content is overwritten in the file, and in case the file does not exist then in that case, a new file is created.
Syntax:
FILE * filePointer; filePointer = fopen(“fileName.txt”, “w+”);
C
#include <stdio.h>
#include <string.h>
int main()
{
FILE * filePointer;
char dataToBeWritten[100]
= "It is a platform"
+ " for learning language"
+ " tech related topics." ;
char dataToBeRead[50];
filePointer = fopen ( "GfgTest.txt" , "w+" );
if (filePointer == NULL) {
printf ( "GfgTest.txt file failed to open." );
}
else {
printf ( "The file is now opened.\n" );
if ( strlen (dataToBeWritten) > 0) {
fprintf (filePointer, dataToBeWritten);
fprintf (filePointer, "\n" );
}
printf ( "Data successfully"
+ " written to the file\n" );
while ( fgets (dataToBeRead, 50,
filePointer)
!= NULL) {
printf ( "%s" , dataToBeRead);
}
printf ( "\nData successfully read"
+ " from file GfgTest.txt" );
fclose (filePointer);
printf ( "\nThe file is now closed." );
}
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...