Programming in C—"File Operations".

in StemSocial6 years ago (edited)

download.png

Image Source

File Operations

There are some operations that can be done by a user regarding files.

  • 1: New file creation.
  • 2: Operating an existing file.
  • 3: File reading and information writing in a file.
  • 4: File closing.
Working With File

In order to work with a file, we need to declare pointer of a type file which is used for communication between file and program.

FILE*fptr

Opening a File

In C-programming, File can be opened by an inbuilt function fopen() available in stdio.h library.
Syntax for opening file:

FILE*fptr=fopen("fileName","mode")

It contains two literals, filename is a string literal which refers to the name of a file to be open along with it's extension also if file is stored in any other directory, user have to specify that path. Mode contains many options. Some option are right below:

File Mode
Meaning of Mode
r
Open's file for reading. - If the file does not exist, fopen() returns NULL.
rb
Opens file for reading binary in binary mode.
w
Opens file for writing.
wb
Opens file for writing in binary mode.
a
Opens file for append, data will be added at end of file.
ab
Opens file for append in binary mode, here also data will get added at en# of file.
r+
It is used for both reading and writing in a file.
rb+
It is used for writing and reading a file in binary mode.

These are few modes which can be used in file processing.
Example:

fptr=fopen("C:\TURBOC3\program.txt","w");

Closing a File

For closing anything, we need first to use it or complete it. The same is the case with file, it should be closed after using or working on it.
Like opening a file, it can be closed by a similar function fclose() available in library.
Syntax for closing file:

fclose(file_pointer);

Here, file_pointer is the name of a file which was created when opening a file by fopen() commond.
Example:
fclose(fptr)

Logo.png

Thank you.

I hope you guys liked my post.

Keep Supporting.

STAY TUNED FOR NEXT TOPIC.

UPVOTECOMMENTRESTEEM
IF YOULIKEDMY POST

Logo.png

Created by @zord189

Stay Safe, Stay Home

@peerzadazeeshan