Upload
lily-sharma
View
219
Download
0
Embed Size (px)
Citation preview
CHAPTER -10
FILE PROCESSING
Contents:
10.0 Introduction
10.1 Objectives
10.2 File operations
10.2.1 Creating a new file
10.2.2 Closing a file
10.3 File input/output functions
10.3.1Character data oriented functions
10.3.2tring data oriented functions
10.3.3!i"ed data oriented functions
10.# $rogra%s using files
10.&u%%ar'
10.( )eview *uestions
10.+ $rogra%%ing ,"ercise
10.0 Introduction
What is a file?
-ith an' C progra% there are two %ajor operations between the user and the progra% which
are
• ow to send data data input to the progra% and
• ow to get results data output fro% the progra%
o far we have done these two operation using the following input/output functions
scanf( )getchar( )gets( )
……..
……
Input
functions
printf( )putchar( )puts( )
……..
……
Output
functions
For e"a%ple the following progra% reads input data and prints the out data
In the above progra% the data that is input through e'board and that is output on the screen
is te%porar' because the data is stored in %ain %e%or'. o whenever the application is
closed or the s'ste% is switched off the entire data on %ain %e%or' is lost. o it not
possible to see the data in future. ince these I/O functions use e'board and screen
these functions are console oriented I/O functions. sing these functions it is not
possible to store data per%anentl' in the s'ste%.
4ut in real application lie student database e%plo'ee database and ban data it is re*uired
to store per%anentl' in the s'ste%. It is possible to store data per%anentl' in the s'ste%
b' using secondar' %e%or'. 5he console I/O functions do not support to handle data
with secondar' %e%or'.
It is therefore necessar' to have a fle"ible approach to operate input and output operations
between a file in secondar' %e%or' and the progra%. 5his can be achieved b' using
FI6, concept.
For e"a%ple assu%e that two files 7I8$5.9:5; and 7),65.9:5; in secondar' %e%or'
and the input/output operations between these files and the progra% shown as follows.
-ith this e"planation we can define what a file
Example1.c
#include<stdio.h>void main( ){ FILE fp1 fp!" int x" fp1fopen($I%&'.*+$,+)" fp!fopen($-E'L.*+$/+)" f scanf(fp1 $0d+ x )" fp,intf(fp! $2n x0d+x)"3
Output
(o the file)
x 4
-E'L.*
4 5 16 1117 18
I%&'.*
Input
(h,ou9h
file)
:he,efscanf( ) ; is file input function used to ,ead data f,om the file to thep,o9,amfp,intf( ) ; is file output function used to /,ite data to the file f,omthe p,o9,am
,"a%ple1.c
<include=stdio.h>
void %ain
?
int "@
printf7An,nter an integerB;@
scanf7d; D" @
printf7An "Ed; "@
3 Output data
On the screen
Output
,nter an integerB &
" E &
Input data
5hrough e'board
: file is so%e reserved space on the dis where a group of related data is stored per%anentl'
in the s'ste%.
,"1B tudent data input with the file na%e 759,85.I8;
,"2B tudent data output with the file na%e 7O5$5.9:5;
10.1 O!ecti"es
tudents are able to
• nderstand FI6, %anage%ent in C
• se file operation functions
• Create and opening a file
• tore large sie of data per%anentl' in the s'ste%
10.# Fi$e oper%tions
5he different basic file operation are
• 8a%ing a file
• Creating / Opening a file
• Closing a file
• -riting data to a file
• )eading data fro% a file
RNO NAME SUB1
SUB2 SUB3
16 -amu 1 14 1=11 opi !6 114
'E%.I%
RNO NAME SUB1 SUB2 SUB3
TOTAL AVG
16 -amu 1 14 1= 8161=.7711 opi !6 1 14 47
15.=5
O'&'.*
C supports a nu%ber of functions that have the abilit' to perfor% basic file operations which
includesB
Function n%&e Oper%tion
fopen - Creates a new file or opens an e"isting file for use
fclose - Closes a file which has been opened for use
getc - )eads a character fro% a file
putc - -rites a character to a file
fprintf - -rites a set of data values to a file
fscanf - )eads a set of data values fro% a file
getw - )eads an integer fro% a file
putw - -rites an integer to a file
fsee - ets the position to a desired point in the file
ftell - Gives the current position in the file
rewind - ets the position to the beginning of the file
10.#.1 Cre%tin' % ne( )i$e * Openin' %n e+istin' )i$e
5o create a new file or to open an e"isting file the function )open, is used.
)open,
Is a file function used to create a new file or used to open an e"isting file. Its general for% is
-here
• )p H is a file pointer which is re*uired to declare using the data structure FILE. 5he
declaration %ust be before it used.
• 5he general for to declare file pointer is
• For e"a%ple
• FI6, p1 p2 fp@
• “filename” H is the na%e of the file and is a string of characters that %ae up a valid
filena%e for the operating s'ste%. It %a' contain two parts a pri%ar' na%e and an
optional period with the e"tension. For e"a%ple
• 7input.data;
• 7store;
• 759,85.9:5;
• 7),65.O5;
fp E )open 7 filename; 7mode; @
FILE *file-
• “mode” H specifies the purpose of opening the file. 5he %ode of the file %a' be one
of the following
• 7w; JJ opens the file for writing purpose
• 7r; JJ opens the file for reading purpose
• 7a; JJ opens the file for appending data to it
E+%&p$e10.1: Create a new file ST/ENT.IN for writing purpose
<include=stdio.h>
void %ain
?
FI6, fp@
fp E fopen 759,85.I8; 7w; @
KKKKKKKK
KKKKKKKK
L
5he 7w; H %ode creates a new file if the file 759,85.I8; is not e"isting in the s'ste%. If
the file 759,85.I8; is e"ist in the s'ste% alread' then it will opens the file freshl'
with loss of old data for writing purpose.
E+%&p$e10.#: Open an e"isting file ST/ENT.IN for data reading purpose
<include=stdio.h>
void %ain
?
FI6, fp@
fp E fopen 759,85.I8; 7r; @
KKKKKKKK
KKKKKKKK
L
5he 7r; H %ode opens the file for reading purpose if the file 759,85.I8; is e"ists in the
s'ste%. If the file 759,85.I8; is not e"ist in the s'ste% then it will rise error.
E+%&p$e10.2: open the file ST/ENT.IN for appending data
<include=stdio.h>
void %ain
?
FI6, fp@
fp E fopen 759,85.I8; 7a; @
KKKKKKKK
KKKKKKKK
L
5he 7a; H %ode creates a new file if the file 759,85.I8; is not e"isting in the s'ste%. If
the file 759,85.I8; is e"ist in the s'ste% alread' then it will opens the file without
loss of old data for writing purpose.
fp59,85.I8
fp 59,85.I8
fp 59,85.I8
10.#.# C$osin' % )i$e
Closing an opened file is b' using the function )c$ose,
)c$ose,
5he fclose is the counterpart of fopen . 5his is to close a file. Closing file %eans
delining the file fro% the progra% and saving the contents of the file. Its general for% is
: file %ust be closed as soon as all operations on it have been co%pleted. 5his would close
the file associated with the file pointer.
Observe the following progra%.
<include=stdio.h>
void %ain
?
FI6, p1 p2@
p1Efopen 7Input;;w;@
p2Efopen 7Output;;r;@
K.
K
fclosep1@
fclosep2
L
5he above progra% opens two files and closes the% after all operations on the% are
co%pleted once a file is closed its file pointer can be reversed on other file.
10.2 Fi$e Input*Output )unctions
:fter a file is opened we can read data stored in the file or write new data onto it depending
on the %ode of opening. C standard librar' supports a good nu%ber of functions which
can be used for perfor%ing I/O operations. File I/O functions are broadl' classified into
two t'pes.
1. igh level file I/O functions
2. 6ow level file I/O functions
igh level file I/O functions are basicall' C standard librar' functions and are eas' to use.
!ost of the C progra%s handling files use these because of their si%ple nature. 6ow
level file I/O functions are file related s'ste% calls of the underl'ing operating s'ste%.
5hese are relativel' %ore co%ple" in nature when co%pared to high level file I/O
functions but efficient in nature. 5he following are the high level file I/O functions
• Character data oriented functions
• tring data oriented functions
)c$ose,)p3
• !i"ed data oriented functions
10.2.1 C4%r%cter d%t% oriented )unctions
• )putc, BJ is to write a character onto a file. Its general for% is
-here the character/char-variable represents a character and fp is a pointer to FI6,.
5he function writes the character or content of charJvariable onto the file represented
b' fp.
E+%&p$e10.5: to create a file for writing characters to it using fputc
<include=stdio.h>
void %ain
?
FI6, fp@
char ch E M:N@
fp E fopen75,5.9:5; 7w; @
fputcch fp@
fputcM4N fp@
fputcMCN fp@
fclosefp@
L
5he file pointer )p writes the content of char variable c4 first and ne"t the character
678 and 6C8 written to the file
• )'etc, BJ is to read a character fro% a file. Its general for% is
5he function reads a character fro% the file denoted b' fp and returns the character
value which is collected b' the charJvariable.
E+%&p$e10.9: to open read a file for reading characters fro% it using fgetc
<include=stdio.h>
void %ain
?
FI6, fp@
char ch1ch2@
fp E fopen75,5.9:5; 7r; @
ch1 E fgetc fp@
ch2 E fgetc fp@
fclosefp@
L
)putc, c4%r%cter*c4%r-"%ri%$e )p3
c4%r-"%ri%$e ; )'etc, )p3
*?@
EA.*
*?@
EA.*
5he file pointer )p reads the content of file 75,5.9:5; . First the character M:N
reads and stored in char variable c41 and ne"t the character 678 reads and stored in
char variable c4#
10.2.# Strin' d%t% oriented )unctions
• )puts, :- is to write a string onto a file. Its general for% is.
-here the string/string-variable represents a string constant and fp is a pointer to
FI6,. 5he function writes the string or content of stringJvariable onto the file
represented b' fp.
E+%&p$e10.<B 5o create a file for writing strings to it using fputs
<include=stdio.h>
void %ain
?
FI6, fp@
char strPQ E 78,-; @
fp E fopen7data.in; 7w; @
fputsstr fp@
fputs7O69; fp@
fputc7O69 O69; fp@
fclosefp@
L
5he file pointer )p writes the content of string variable str first and ne"t the strings
7O69; and 7O69 O69; written to the file
• )'ets, BJ is to read a string fro% a file. Its general for% is
5he function reads a string fro% the file denoted b' fp and returns the string value
which is collected b' the stringJvariable.
E+%&p$e10.=B 5o open the file for reading strings fro% it using fputs
<include=stdio.h>
void %ain
?
FI6, fp@
char str1P Q strP Q@
fp E fopen7data.in; 7r; @
fgetsstr1 fp@
fgetsstr2 fp@
fclosefp@
L
)puts, strin'*strin'-"%ri%$e )p3
)'etc,strin'-"%ri%$e )p3
%E: OL
OL OL
**.I%
%E:OL
OL OL
**.I%
5he file pointer )p reads the content of file 79:5:.I8; . First the string 78,-; reads
and stored in string variable str1 and ne"t the string 7O69; reads and stored in string
variable str#
10.2.2 >i+ed d%t% oriented )unctions
• )print), :- is to write %ultiple data ite%s which %a' or not be of different t'pes to
a file. Its general for% is.
-here )p is a pointer to FI6, 7contro$-strin'; is the for%at of data to be write and
%r'1 %r'# ? are the argu%ents list. 5he function writes the data values of arg1
arg2K onto the file represented b' fp.
E+%&p$e10.10B 5o create a file for writing student details to it using fprintf
<include=stdio.h>
void %ain
?
FI6, fp@
char na%eP30Q E 7):!;@
int rollno E 2&@
float totalR%ars E #&0@
fp E fopen759,85.9:5; 7w; @
fprintf fp 7AndAtsAtf; rollno na%e totalR%ars@
fclosefp@
L
5he file pointer )p writes the content of rollno na%e and totalR%ars variables written to the
file
• )sc%n), BJ is to read %ultiple data ite%s which %a' be of different t'pes fro% a file.
Its general for% is
5he function reads data values in a given for%at fro% the file denoted b' fp and
returns the data values which are collected b' the argu%ents list..
E+%&p$e10.10B 5o open the file for reading student details fro% it using fscanf
<include=stdio.h>
void %ain
?
FI6, fp@
char na%eP30Q@
int rollno@
float totalR%ar @
fp E fopen759,85.9:5; 7r; @
fprintf fp7dsf; Drollnona%eDtotalR%ars@
fclosefp@
L
)print), )p contro$-strin' %r'1 %r'# %r'2?????..3
!4 -*BO 846
'E%.I%
)sc%n), )p contro$-strin' %r'1 %r'# %r'2?????..3
!4 -*BO 846
'E%.I%
5he file pointer fp reads data values fro% the file 759,85.I8; and returns the values
which are collected b' rollno na%e and totalR%ars correspondingl'.
10.@ Pro'r%&s usin' )i$es
8ow out input %a' be through e'board or a file and output to the screen or to a file.
$rogra%s using files %a' involve the co%binations of these different input/output
operations and shown as followsB
Pro'10.1: -rite a progra% that reads character b' character through e'board and writes to
the file 7I8$5; the end of the data is indicated b' entering an ,OF character which is
controlJ. later open the file 7I8$5; for reading the data and print on the standard output.
<include= stdio.h >
%ain
?
file f1@ char c@
printf79ata input output;@
f1Efopen7I8$5; 7w;@ /Open the file Input/
whilecEgetcharSE,OF /get a character fro% e' board/
putcc f1@ /write a character to input/
fclosef1@ /close the file input/
printf7An9ata outputAn;@
f1Efopen7I8$5; 7r;@ /)eopen the file input/
whilecEgetcf1SE,OF
printf7c; c@
fclosef1@
L
,"a%ple1.c
<include=stdio.h>
void %ain
?
KKKKKK.
KKKKKK.
KKKKKK.
KKKKKK.
3
Output data
On the screen
&utcha,() puts() p,intf()
Input data
5hrough e'board
9etcha,() 9ets()scanf()
Input(h,ou9h file)
f9etc() f9ets()fscanf()
Output(o the file)
Fputc() fputs() fp,intf()
x 4
-E'L.*
4 5 16 1117 18
I%&'.*
Pro'10.#: write a progra% to read integers trough e' board and write to the file 79:5:;.
6ater read the data fro% the file 79:5:; and write even nu%bers to the file 7,T,8; and
odd nu%bers to the file 7O99;. )ead data fro% the files 7,T,8; 7O99; and displa' on the
standard output
/,"a%ple progra% for using getw and putw functions/
<include= stdio.h >
%ain
?
FI6, f1f2f3@
int nu%ber I@
printf7Contents of the data fileAnAn;@
f1Efopen79:5:;;-;@
forIE1@I= 30@IUU
?
scanf7d;Dnu%ber@
ifnu%berEEJ1
brea@
putwnu%berf1@
L
fclosef1@
f1Efopen79:5:;;r;@
f2Efopen7O99;;w;@
f3Efopen7,T,8;;w;@
whilenu%berEgetwf1SE,OF / )ead fro% data file/
?
ifnu%ber2EE0
putwnu%berf3@ /-rite to even file/
else
putwnu%berf2@ /write to odd file/
L
fclosef1@
fclosef2@
fclosef3@
f2Efopen7O99; ;r;@
f3Efopen7,T,8; ;r;@
printf7AnAnContents of the odd fileAnAn;@
whilenu%berEgetwf2SE,OF
printf7dd;nu%ber@
printf7AnAnContents of the even file;@
whilenu%berEgetwf3SE,OF
printf7d;nu%ber@
fclosef2@
fclosef3@
L
Pro'10.2: progra% to read inventor' data@ ite% nu%ber price and *uantit' for three ite%s
and writes the data to the file. 6ater read the data fro% the file and displa' on the screen with
total value.
/$rogra% to handle %i"ed data t'pes/
<include= stdio.h >
%ain
?
FI6, fp@
int nu%*t'i@
float pricevalue@
char ite%P10Qfilena%eP10Q@
printf7Input filena%e;@
scanf7s;filena%e@
fpEfopenfilena%e;w;@
printf7Input inventor' dataAnAn;@
printf7Ite%Rna%e nu%ber price and *uantit'An;@
for iE1@ i= E3@ iUU
?
scanf;sdfd; ite% Dnu%ber Dprice D*ualit'@
fprintffp;sdfd; ite% nu%ber price *ualit'@
L
fclose fp@
fpEfopenfilena%e;r;@
printf7AnIte%R na%e At 8u%ber At $rice At Vuantit' At Talue;@
forIE1@I= E3@IUU
?
fscanffp;sdfd;ite%Dnu%berDprinceD*ualit'@
valueEprice*uantit'@
printf;Ans At d At f At d At d;ite% nu%ber price *uantit' value@
L
fclosefp@
L
Pro'10.@: 9efine a structure e%p with %e%bers as e%pno na%e and salar'. -rite a progra%
to read infor%ation for n nu%ber of e%plo'ees and write this data to the file
M,!$.9:5;. 6ater read the data fro% the file and displa' on standard output.
<include=stdio.h>
struct e%p
?
int e%pno@
char na%eP30Q@
float salar'@
L
void %ain
?
int ni@
FI6, fp@
struct e%p e@
fp E fopen7,!$.9:5; 7w;@
printf7An,nter no of e%plo'eesB;@
scanf7d; Dn@
printf7An ,nter e%pno na%e and sal for d no of e%plo'eesBAn; n@
foriE0@ i=n@ UUi
?
scanf7dsf; De.e%pno e.na%e De.salar'@
fprintffp 7AndAtsAtf; e.e%pno e.na%e e.salar'@
L
fclosefp@
fpEfopen7,!$.9:5; 7r;@
printf7AnContents of the file ,!$.9:5;@
whileSfeoffp
?
fscanffp 7dsf; De.e%pno e.na%e De.salar'@
printf7AndAtsAtf; e.e%pno e.na%e e.salar'@
L
fclosefp@
L
10.5 Su&&%r
)eal life situations involve large volu%e of data and in such cases@ the console oriented I/O
operations pose two %ajor proble%s. It beco%es cu%berso%e and ti%e consu%ing to handle
large volu%es of data through ter%inals. 5he entire data is lost when either the progra% is
ter%inated or co%puter is turned off therefore it is necessar' to have %ore fle"ible approach
where data can be stored on the diss and read whenever necessar' without destro'ing the
data. 5his %ethod e%plo's the concept of files to store data.
5he concept of files enables us to store large a%ount of data per%anentl' on the secondar'
storage devices. : variable of t'pe FI6, is used to represent a file within progra%. It acts
as an internal file na%e for a file. 4efore perfor%ing an' operation over a file it has to
be opened. 5he purpose of the opened file %a' be for writing data or reading data or %a'
be for appending data to the file. Once the intended operation is over the file has to be
closed. 5he file input/output operations are b' using the functions )'etc, )putc,
which are the character oriented file I/O functions )'ets, )puts, are the string oriented
functions and )sc%n), %nd )print), are the %i"ed data oriented functions.
5he function )seeB, is used to %ove the file pointer to the re*uired b'te in a file and the
function )te$$, is used to now the position of the file pointer in a file.
10.9 Re"ie( uestions
1. -hat is a fileW -h' do we need the concept of filesW
2. -hat are the %ost co%%onl' perfor%ed operations over filesW
3. -hat are the different %odes of opening a fileW
#. -hat is the difference between 7w; and 7a;W
&. !ention character oriented file I/O functions and s'nta" of their usage
(. ,"plain the s'nta" and usage of fprintf and fscanf
+. File is a na%ed storage on the secondar' storage device 5), / F:6,
X. : file should be first opened before perfor%ing an' operation 5), / F:6,
Y. -hen a file is opened in 7w; %ode the previous contents re%ain intact 5rue /False
10. -hen a file is opened in 7a; %ode the previous contents are lost 5rue / False
11. Identif' the error
a FI6, fp@
fp E fopen7te"t.dat; 7w;@
b FI6, fin@
fin E fopen7te"t.dat; r @
c FI6, fp1 fp2@
fp1 E fopen7te"t.dat; 7w;@
fp2 E fopen7te"t.dat; 7r;@
10.< pro'r%&&in' E+ercises
1. -rite a progra% using a for loop to put the following nu%bers to a file na%ed
7record.dat;. 1 2 3 # & ( + X 10 10
2. -rite a progra% to read the file 7record.dat; created in the above proble% and print
out as standard output
3. -rite a progra% to save the following se*uence of nu%bers in a file na%ed
7nu%ber.dat;. 5hen read the data in this file and write even nu%bers to the file
7even.dat; and odd nu%bers to the file 7odd.dat;.
#. -rite a progra% to count the nu%ber of characters in a te"t file.
&. -rite a progra% to cop' the content of one te"t file to another te"t file
(. -rite a progra% to sort a file consisting of na%es of students and displa' the%