Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

File Handling in C

File.
A file is used for permanent storage.
Opening a file.
FILE *fp;
fp is a file pointer variable which contains address of structure FILE
which is defined in stdio.h
fopen(file-name,opening mode);
file-name name of the file to open.
opening-mode mode in which is file is to be opened. This may be:
r reading mode.
w writing mode.
a appending mode.
e.g. fopen(abc.txt,r);
it will open file in reading mode. Means we can only read
its data.

Creating new file.


fopen(abc.txt, w);
it will open file in writing mode means you can only write
to this file. If name of the file file is not existing then it
creates new blank file.
caution: if you create an existing file in writing mode,
then its previous contents gets destroyed.
fopen(abc.txt, a);
it will open the existing file in appending mode. In this
case the previous contents doesnt get destroyed you
can only append new data to this file.

Reading from a file.


fscanf is used to read the contents from the file.
Syntax:
fscanf(file-pointer,access-specifier,variables);
e.g. FILE *fp;
char name[10];
fp = fopen(abc.txt, r);
fscanf(fp,%s, name);
printf(%s, name);
Print to output

fscanf

name

name

File

Writing to a file
fprintf is used to write the contents to the file.
Syntax:
fscanf(file-pointer,access-specifier,variables);
e.g. FILE *fp;
char name[10];
fp = fopen(abc.txt, w);
fprintf(fp,Your name : KKWP);
This will print Your name : KKWP
in the file name abc.txt.

Some file operations.


fclose(file-pointer);
when you open a file using fopen() is must be closed
using this statement after use.
e.g. fclose(fp);
Checking exiting file:
if(fp==NULL)
then file is not existing.
feof(file-pointer)
it checks that end of file is reached or not. If yes returns
1 else false.
e.g. while(feof(fp))
fscanf(fp,%s, name);

Created By,
Mr.

Tushar B Kute,

Lecturer in Information Technology,


K. K. Wagh Polytechnic, Nashik.
tbkute@gmail.com

You might also like