Вы находитесь на странице: 1из 14

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.2 tring 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 /input0 to the progra% and .ow to get results data /output0 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 ,"a%ple1.c <include=stdio.h> void %ain/ 0 ? int "@ printf/7An,nter an integerB;0@ scanf/7Cd;2 D" 0@ printf/7An "ECd;2 "0@ Input data /5hrough 1e'board0
3

Output data /On the screen0

Output ,nter an integerB & "E&

In the above progra% the data that is input through 1e'board and that is output on the screen is te%porar'2 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 1e'board and screen2 these functions are console oriented I/O functions. 3sing these functions it is not possible to store data per%anentl' in the s'ste%. 4ut in real application li1e student database2 e%plo'ee database and ban1 data2 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$35.9:5; and 7), 365.9:5; in secondar' %e%or' and the input/output operations between these files and the progra% shown as follows.
I%&'(.)*( 4 5 16 11 17 18 Example1.c #include<stdio.h> void main( ) { FILE fp1 fp!" int x" fp1#fopen($I%&'(.)*(+ $,+)" -E.'L(.)*( x#4

fp!#fopen($-E.'L(.)*(+ $/+)" f scanf(fp1 $0d+ 1x )" fp,intf(fp! $2n x#0d+ x)" :he,e 3 function used to ,ead data f,om the file to the fscanf( ) ; is file input p,o9,am -ith this e"planation define what a file fp,intf( ) ; is we filecan output function used to /,ite data to the file f,om the p,o9,am

Input ((h,ou9h file)

Output ((o the file)

: file is so%e reserved space on the dis1 where a group of related data is stored per%anentl' in the s'ste%. ,"1B tudent data input with the file na%e 7 539,85.I8;
.(')E%(.I% RNO NAME SUB2 SUB3 16 11 14 SUB1

-amu 1< 14 1= >opi !6 1<

,"2B tudent data output with the file na%e 7O35$35.9:5;


O'(&'(.)*( RNO NAME SUB1 SUB2 SUB3 TOTAL AVG 16 -amu 1< 14 1= 1=.77 11 >opi !6 1< 15.=5 816 14 47

10.1 O !ecti"es
tudents are able to 3nderstand FI6, %anage%ent in C 3se file operation functions Create and opening a file tore large siFe 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

C supports a nu%ber of functions that have the abilit' to perfor% basic file operations2 which includesB Function n%&e fopen/ 0 fclose/ 0 getc/ 0 putc/ 0 fprintf/ 0 fscanf/ 0 getw/ 0 putw/ 0 fsee1/ 0 ftell/ 0 rewind/ 0 Oper%tion Creates a new file or opens an e"isting file for use Closes a file which has been opened for use )eads a character fro% a file -rites a character to a file -rites a set of data values to a file )eads a set of data values fro% a file )eads an integer fro% a file -rites an integer to a file ets the position to a desired point in the file Gives the current position in the file 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 fp E )open / 7filename;2 7mode; 0@

-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 FILE *file For e"a%ple FI6, Ip12 Ip22 Ifp@

filename H is the na%e of the file and is a string of characters that %a1e up a valid filena%e for the operating s'ste%. It %a' contain two parts2 a pri%ar' na%e and an optional period with the e"tension. For e"a%ple 7input.data; 7store; 7 539,85.9:5; 7), 365 .O35;

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/0ENT.IN1 for writing purpose <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ fp E fopen/ 7 539,85.I8; 2 7w; 0@ KKKKKKKK KKKKKKKK L fp 539,85.I8

5he 7w; H %ode creates a new file if the file 7 539,85.I8; is not e"isting in the s'ste%. If the file 7 539,85.I8; is e"ist in the s'ste% alread' then it will opens the file freshl' /with loss of old data0 for writing purpose. E+%&p$e10.#: Open an e"isting file .ST/0ENT.IN1 for data reading purpose 539,85.I8 <include=stdio.h> fp void %ain/ 0 ? FI6, Ifp@ fp E fopen/ 7 539,85.I8; 2 7r; 0@ KKKKKKKK KKKKKKKK L 5he 7r; H %ode opens the file for reading purpose if the file 7 539,85.I8; is e"ists in the s'ste%. If the file 7 539,85.I8; is not e"ist in the s'ste% then it will rise error. E+%&p$e10.2: open the file .ST/0ENT.IN1 for appending data <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ fp E fopen/ 7 539,85.I8; 2 7a; 0@ KKKKKKKK KKKKKKKK L fp 539,85.I8

5he 7a; H %ode creates a new file if the file 7 539,85.I8; is not e"isting in the s'ste%. If the file 7 539,85.I8; is e"ist in the s'ste% alread' then it will opens the file /without loss of old data0 for writing purpose.

10.#.# C$osin' % )i$e Closing an opened file is b' using the function )c$ose, )c$ose, 5he fclose/ 0 is the counterpart of fopen/ 0. 5his is to close a file. Closing file %eans delin1ing the file fro% the progra% and saving the contents of the file. Its general for% is )c$ose,)p-3 : 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/ 0 ? FI6, Ip1 Ip2@ p1Efopen /7Input;2;w;0@ p2Efopen /7Output;2;r;0@ K. K fclose/p10@ fclose/p20 L 5he above progra% opens two files and closes the% after all operations on the% are co%pleted2 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 opened2 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

!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 )putc, c4%r%cter*c4%r-"%ri% $e: )p-3 -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/ 0 <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ char ch E M:N@ fp E fopen/75,O5.9:5; 2 7w; 0@ fputc/ch 2 fp0@ fputc/M4N2 fp0@ fputc/MCN2 fp0@ fclose/fp0@ L

(EA(.)*( *?@

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 c4%r-"%ri% $e ; )'etc, )p-3 5he function reads a character fro% the file denoted b' fp and returns the character value2 which is collected b' the charJvariable. E+%&p$e10.9: to open read a file for reading characters fro% it using fgetc/ 0 <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ char ch12ch2@ fp E fopen/75,O5.9:5; 2 7r; 0@ ch1 E fgetc/ fp0@ ch2 E fgetc/ fp0@ fclose/fp0@ L

(EA(.)*( *?@

5he file pointer )p reads the content of file 75,O5.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. )puts, strin'*strin'-"%ri% $e: )p-3 -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/ 0 <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ char strPQ E 78,-; @ fp E fopen/7data.in; 2 7w; 0@ fputs/str 2 fp0@ fputs/7O69; 2 fp0@ fputc/7O69 O69;2 fp0@ fclose/fp0@ L

)*(*.I% %E: OL) OL) OL)

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 )'etc,strin'-"%ri% $e : )p-3 5he function reads a string fro% the file denoted b' fp and returns the string value2 which is collected b' the stringJvariable. E+%&p$e10.=B 5o open the file for reading strings fro% it using fputs/ 0 <include=stdio.h> void %ain/ 0 ? FI6, Ifp@ char str1P Q2 strP Q@ fp E fopen/7data.in; 2 7r; 0@ fgets/str12 fp0@ fgets/str22 fp0@ fclose/fp0@ L

)*(*.I% %E: OL) OL) OL)

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 not0 be of different t'pes to a file. Its general for% is. )print), )p: .contro$-strin'1: %r'1: %r'#: %r'2:?????..-3 -here )p is a pointer to FI6,2 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 arg12 arg2K onto the file represented b' fp. E+%&p$e10.10B 5o create a file for writing student details to it using fprintf/ 0 <include=stdio.h> void %ain/ 0 ? .(')E%(.I% FI6, Ifp@ !4 -*BO char na%eP30Q E 7):!3;@ int rollno E 2&@ float totalR%ar1s E #&0@ fp E fopen/7 539,85.9:5; 2 7w; 0@ fprintf/ fp2 7AnCdAtCsAtCf;2 rollno2 na%e2 totalR%ar1s0@ fclose/fp0@ L

846

5he file pointer )p writes the content of rollno2 na%e and totalR%ar1s 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 )sc%n), )p: .contro$-strin'1: %r'1: %r'#: %r'2:?????..-3 5he function reads data values in a given for%at fro% the file denoted b' fp and returns the data values2 which are collected b' the argu%ents list.. E+%&p$e10.10B 5o open the file for reading student details fro% it using fscanf/ 0 <include=stdio.h> void %ain/ 0 ? .(')E%(.I% FI6, Ifp@ !4 -*BO 846 char na%eP30Q@ int rollno@ float totalR%ar1 @ fp E fopen/7 539,85.9:5; 2 7r; 0@ fprintf/ fp27CdCsCf;2 Drollno2na%e2DtotalR%ar1s0@ fclose/fp0@ L

5he file pointer fp reads data values fro% the file 7 539,85.I8; and returns the values which are collected b' rollno2 na%e and totalR%ar1s correspondingl'.

10.@ Pro'r%&s usin' )i$es


8ow out input %a' be through 1e'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
I%&'(.)*( 4 5 16 11 17 18 Input ((h,ou9h file) f9etc() f9ets() fscanf() -E.'L(.)*(

,"a%ple1.c <include=stdio.h> void %ain/ 0 ? KKKKKK. KKKKKK. KKKKKK. KKKKKK.


3

x#4 Output ((o the file) Fputc() fputs() fp,intf()

Input data /5hrough 1e'board0


9etcha,() 9ets() scanf()

Output data /On the screen0


&utcha,() puts() p,intf()

Pro'10.1: -rite a progra% that reads character b' character through 1e'board and writes to the file 7I8$35;2 the end of the data is indicated b' entering an ,OF character2 which is controlJF. later open the file 7I8$35; for reading the data and print on the standard output. <include= stdio.h > %ain/0 ? file If1@ char c@ printf/79ata input output;0@ f1Efopen/7I8$35;2 7w;0@ while//cEgetchar/00SE,OF0 putc/c2 f10@ fclose/f10@ printf/7An9ata outputAn;0@ f1Efopen/7I8$35;2 7r;0@ while//cEgetc/f100SE,OF0 printf/7Cc;2 c0@ fclose/f10@ L

/IOpen the file InputI/ /Iget a character fro% 1e' boardI/ /Iwrite a character to inputI/ /Iclose the file inputI/ /I)eopen the file inputI/

Pro'10.#: write a progra% to read integers trough 1e' board and write to the file 79:5:;. 6ater read the data fro% the file 79:5:;2 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;2 7O99; and displa' on the standard output /I,"a%ple progra% for using getw and putw functionsI/ <include= stdio.h > %ain/0 ? FI6, If12If22If3@ int nu%ber I@ printf/7Contents of the data fileAnAn;0@ f1Efopen/79:5:;2;-;0@ for/IE1@I= 30@IUU0 ? scanf/7Cd;2Dnu%ber0@ if/nu%berEEJ10 brea1@ putw/nu%ber2f10@ L fclose/f10@ f1Efopen/79:5:;2;r;0@ f2Efopen/7O99;2;w;0@ f3Efopen/7,T,8;2;w;0@ while//nu%berEgetw/f100SE,OF0 /I )ead fro% data fileI/ ? if/nu%berC2EE00 putw/nu%ber2f30@ /I-rite to even fileI/ else putw/nu%ber2f20@ /Iwrite to odd fileI/ L fclose/f10@ fclose/f20@ fclose/f30@ f2Efopen/7O99;2 ;r;0@ f3Efopen/7,T,8;2 ;r;0@ printf/7AnAnContents of the odd fileAnAn;0@ while/nu%berEgetw/f200SE,OF0 printf/7CdCd;2nu%ber0@ printf/7AnAnContents of the even file;0@ while/nu%berEgetw/f300SE,OF0 printf/7Cd;2nu%ber0@ fclose/f20@ fclose/f30@ L

Pro'10.2: progra% to read inventor' data@ ite%2 nu%ber2 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. /I$rogra% to handle %i"ed data t'pesI/ <include= stdio.h > %ain/0 ? FI6, Ifp@ int nu%2*t'2i@ float price2value@ char ite%P10Q2filena%eP10Q@ printf/7Input filena%e;0@ scanf/7Cs;2filena%e0@ fpEfopen/filena%e2;w;0@ printf/7Input inventor' dataAnAn;0@ printf/7Ite%Rna%e2 nu%ber2 price and *uantit'An;0@ for iE1@ i= E3@ iUU0 ? scanf/;CsCdCfCd;2 ite%2 Dnu%ber2 Dprice2 D*ualit'0@ fprintf/fp2;CsCdCfCd;2 ite%2 nu%ber2 price2 *ualit'0@ L fclose /fp0@ fpEfopen/filena%e2;r;0@ printf/7AnIte%R na%e At 8u%ber At $rice At Vuantit' At Talue;0@ for/IE1@I= E3@IUU0 ? fscanf/fp2;CsCdCfCd;2ite%2Dnu%ber2Dprince2D*ualit'0@ valueEpriceI*uantit'@ printf/;AnCs At Cd At Cf At Cd At Cd;2ite%2 nu%ber2 price2 *uantit'2 value0@ L fclose/fp0@ L Pro'10.@: 9efine a structure e%p with %e%bers as e%pno2 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/ 0 ? int n2i@ FI6, Ifp@ struct e%p e@

fp E fopen/7,!$.9:5;2 7w;0@ printf/7An,nter no of e%plo'eesB;0@ scanf/7Cd;2 Dn0@ printf/7An ,nter e%pno2 na%e and sal for Cd no of e%plo'eesBAn;2 n0@ for/iE0@ i=n@ UUi0 ? scanf/7CdCsCf;2 De.e%pno2 e.na%e2 De.salar'0@ fprintf/fp2 7AnCdAtCsAtCf;2 e.e%pno2 e.na%e2 e.salar'0@ L fclose/fp0@ fpEfopen/7,!$.9:5;2 7r;0@ printf/7AnContents of the file ,!$.9:5;0@ while/Sfeof/fp00 ? fscanf/fp2 7CdCsCf;2 De.e%pno2 e.na%e2 De.salar'0@ printf/7AnCdAtCsAtCf;2 e.e%pno2 e.na%e2 e.salar'0@ L fclose/fp0@ L

10.5 Su&&%rA
)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 dis1s and read whenever necessar'2 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 file2 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 functions2 )'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 1now the position of the file pointer in a file.

10.9 Re"ie( Cuestions


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/ 0 and fscanf/ 0 +. File is a na%ed storage on the secondar' storage device 5)3, / F:6 , X. : file should be first opened before perfor%ing an' operation 5)3, / F:6 , Y. -hen a file is opened in 7w; %ode2 the previous contents re%ain intact 5rue /False 10. -hen a file is opened in 7a; %ode2 the previous contents are lost 5rue / False 11. Identif' the error a0 FI6, fp@ fp E fopen/7te"t.dat;2 7w;0@ b0 FI6, Ifin@ fin E fopen/7te"t.dat;2 r 0@ c0 FI6, Ifp12 Ifp2@ fp1 E fopen/7te"t.dat;2 7w;0@ fp2 E fopen/7te"t.dat;2 7r;0@

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%

Вам также может понравиться