Opening and Creating a file in different Modes

Filter Course


Opening and Creating a file in different Modes

Published by: Zaya

Published date: 18 Jun 2021

Opening and Creating a file in different Modes Photo

Opening and Creating a file in different modes

C File management

A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file management functions,

  1. Creation of a file
  2. Opening a file
  3. Reading a file
  4. Writing to a file
  5. Closing a file

Following are the most important file management functions available in ‘C,’
function purpose
File

How to Create a File
Whenever you want to work with a file, the first step is to create a file. A file is nothing but space in a memory where data is stored.

To create a file in a ‘C’ program following syntax is used,

FILE *fp;
fp = fopen (“file_name”, “mode”);

In the above syntax, the file is a data structure which is defined in the standard library.

  • fopen is a standard function which is used to open a file.
  • If the file is not present on the system, then it is created and then opened.
  • If a file is already present on the system, then it is directly opened using this function.
  • fp is a file pointer which points to the type file.

 

Whenever you open or create a file, you have to specify what you are going to do with the file. A file in ‘C’ programming can be created or opened for reading/writing purposes. A mode is used to specify whether you want to open a file for any of the below-given purposes. Following are the different types of modes in ‘C’ programming which can be used while working with a file.

File Mode Description
r  Open a file for reading. If a file is in reading mode, then no data is deleted if a  file is already present on a system.w  Open a file for writing. If a file is in writing mode, then a new file is created if a file doesn’t exist at all. If a file is already present on a system, then all the data inside the file is truncated, and it is opened for writing purposes. an Open a file in append mode. If a file is in append mode, then the file is opened. The content within the file doesn’t change.

Column

In the given syntax, the filename and the mode are specified as strings hence they must always be enclosed within double-quotes.

Example:

#include
int main() {
FILE *fp;
fp = fopen (“data.txt”, “w”);
}

Output:
File is created in the same folder where you have saved your code.

adadadad