8 File Handling in C'
8 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 doesn’t 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);