Sunteți pe pagina 1din 15

FILES A file is a place on disk where group of related data are stored.

C supports a number of functions that have the ability to perform basic file operations, which include: Naming a file Opening the file Reading data from the file riting data to the file Closing the file

!here are two distinct ways to perform file operations in C. !he first one is known as the low level "#O and uses $N"% system ,calls. !he second method is referred to as the high level "#O operation and uses functions in C&s standard "#O library. FILE TYPES: 'O( treats files in two different ways vi)., as binary or te*t files. Almost all $N"% (ystems do not make any distinction between the two. "f a file is specified as the binary type, the file "#O functions do not interpret the contents of the file when they read from or write to the+ file. ,ut, if the file is specified as the te*t type the "#O functions interpret the contents of the file. !he basic differences in these two types of files are: ". A(C"" -*la is considered an end.of.file character by the file "#O function when reading from a te*t file and they assume that the end of the file has been reached. "". "n case of 'O( a new file is stored as the se/uence -0-d -0-a on the disk in case of te*t files. $N"% stores 1n as -0 -a both on disk and in memory. FILE Operations: 1. Opening a File: C communicates with files using a new data type called a file pointer. !his type is defined within stdio. h, and written as 2"34 0. A file pointer called output5file is declared in a statement like e 2"34 0output5file6 "f we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. !hey include the filename, data structure, purpose. !he general format of the function used for opening a file is 2"34 0fp6 2p 7 fopen89filename9, 9mode9:6

!he first statement declares the variable fp as a pointer to the data type 2"34. As stated earlier, 2ile is a structure that is defined in the "#O 3ibrary. !he second statement opens the file named filename and assigns an identifier to the 2"34 t:ipe pointer fp. !his pointer, which contains all the information about the file, is subse/uently used as a communication link between the system and the program. !he second statement also specifies the purpose of opening the file. !he mode does this ;ob. r open the file for read only. w open the file for writing only. a open the file for appending data to it. r< open an e*isting file for update 8reading and writing: w< create a new file for update. "f it already e*ists, it will be overwritten. a< open for append6 open for update at the end of the file Consider the following statements: 2"34 0pl, 0p=6 p" 7fopen89data9 ,9r9:6 p=7fopen89results9, 9w9:6 "n these statements the p" and p= are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. "n case the results file already e*ists, its contents are deleted and the files are opened as a new file. "f the data file does not e*ist error will occur. 2. Closing the File: !he input output library supports the function to close a file6 it is in the following format. f close8file .&pointer:6 A file must be closed as soon as all operations on it have been completed. !his would close the file associated with the file pointer. Observe the following program .. 2"34 0p > 0p=6 ?l 7 fopen 89"nput9,9w9:6 p= 7 fopen 89Output9 ,9r9:6 @@ @@ fclose8p >:6 fclose8p=: !he above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.

Reading a character fro f$nctions#

a file and !riting a character into a file " getc "# and putc 8:&

!he getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. !he putc function writes the character contained in character variable c to the file associated with the pointer fp". e* putc8c,fpl:6 similarly getc function is used to read a character from a file that has been open in read mode. c7getc8fp=:. !he program shown below displays use of a file operations. !he data enter through the keyboard and the program. writes it. Character by character, to the file input. !he end of the data is indicated by entering an 4O2 character, which is control.). the file input is closed at this signal. (ample program for using getc and putc functions0#.: AincludeB stdio.h > void mainO { 2"34 0fl6 printf89'ata input output9:6 fl 7fopen89"nput9,9w9:6 #0Open the file "nput0# whileCc7getcharO:D74O2: #0get a character from key board0# putc8 c,fl:6 #0write a character to input0 # fclose8fl:6 #0close the file input0 # printf89'ata output9:6 fl 7fopen89"N?$!9 ,9r9:6 #0Reopen the file input0 # whileC c7getc8fl ::D74O2: printf89Ec9,c :6 fclose8fl :6 F %. Reading a integer fro f$nctions# a file and !riting a integer into a file " get!"# and p$t!"#

!hese are integer.oriented functions. !hey are similar to get c and putc functions and are used to read and write integer values. !hese functions would be usefull when we deal with only integer data. !he general forms of getw and putw are: putw8integer,fp :6 getw8fp:6

#04*ample program for using getw and putw functions 0 # AincludeB stdio.h > void main8 : G 2"34 0fl, 0f=, 0fH6 int number,i6 printf89Contents of the data filenn9:6 fl 7fopen89'A ! A9,9 9:6 for8i7l6iB H-6i<<: G print89enter the number9:6 scanf89Ed9 ,Inumber:6 if8number7 7.l: break6 putw 8number,fl :6 } fclose8fl:6 fl 7fopen89'A ! A9,9r9:6 f=7fopen89O''9, 9w9:6 fH 7fopen 894J4N9, 9w9:6 while88number7getw8fl::D74O2:#0 Read from data file0# G if8numberE=7-: putw8number,fH:6#0 rite to even file0# else putw8number,f=:6#0write to odd file0# } fclose8fl :6 fclose8f=:6 fclose8fH:6 f=7fopen89O ''9 ,9r9:6 fH 7fopen894J4N9, 9r9:6 printf89nnContents of the odd filenn9:6 while8number7getw8f=::D 7 4O 2: printf89Ed9 ,number:6 printf89nnContents of the even file9:6 while8number7getw8fH::D 7 4?2: printf89Ed9 ,number:6 fclose8f=:6 fclose8fH:6 }

&. fscanf"# and fprintf"# f$nctions: !he fprintf and fscanf functions are identical to printf and scanf functions e*cept that they work on files. !he first argument of theses functions is a file pointer which specifies the file to be used. !he general form of fprintf is fprintf8fp,9control string9, list:6 here fp id a file pointer associated with a file that has been opened for writing. !he control string is fiKe output specifications list may include variable, constant and string. fprintf8fl ,EsEdEf9,name,age,L .M:6 Nere name is an array variable of type char and age is an int variable !he general format of fscanf is fscanf8fp,9controlstring9 ,list:6 !his statement would cause the reading of items in the control string. E'a ple: fscanf8 f3,9M sEd9 ,item, I /uantity9:6 3ike scanf, fscanf also returns the number of items that are successfully read. "0?rogram to handle mi*ed data types0# AincludeB stdio.h > main8: G 2"34 0fp6 int num,/ty,i6 float price,value6 char itemO>-P, flemupeO>-P6 printf89enter the filename9:6 scanf89Es9 ,filename:6 fp7fopen8 filename, 9w9:6 printf89"nput inventory data9:6 printf89"tem namem number price /uantity9:6 for 8i7l6iB 7H6i<<: G fscanf8 stdin, 9EsEd EfEd9 ,item,Inumber ,Iprice,I/uality:6 fprintf8 fp, 9EsEdEfl,lod9 ,itemnumber, price, /uality :6 F fclose 8fp:6

fprintf8 stdout, 9nn9:6 fp7fopen8 filename, 9r9:6 printf 89"tem name number price /uantity value9:6 for8i7l6iB 7H6i<<: { fscanf8 fp, 9EsEd Ef>l,lod9 ,item, Inumber ,Iprince, I/uality:6 value7price0/uantity6 fprintf89stdout, 9EsEdEf>l,lod Edn9 ,item, number ,price, /uantity , val ue:6 } fclose8fp :6 } (. fgetc "# and fp$tc"# f$nctions: fgetc8: function is similar to getc8: function. "t also reads a character and increases the file pointer position. "f any error or end of the file is reached it returned 4O2. fputc8: function writes the character to the file shown by the file pointer. "t also increases the file pointer position. Sa ple progra $sing fgetc"# to !rite te't to a file $sing fp$tc"# and read the te't fro the sa e file

AincludeBstdio.hQ void main8: { 2"34 0fp6 char c6 fp7fopen89lines. t*t9, 9w9:6 while8 8 c7getcharO 1 7& 0.&: fputc8 c,fp:6 fclose8fp:6 fp7fopen89lines. t*t9 ,9r9:6 while88 c7fgetc8fp ::D74O2: printf89Ec9,c :6 fclose8fp:6 F ). fgets"# and fp$ts"# f$nctions: fgets8: function reads string from a file pointed by file pointer. "t also copies the string to a memory location referred by an array. fputs8: function is useful when we want to write a string into the opened file . .. Sa ple progra to !rite string to a file $sing fp$ts"# and read the string fro file $sing fgets"# Aincl udeBstdio .hQ void main8: { 2"34 0fp6 Char file O >=P,te*tO M-P6 fp 7 fopen89line. t*t9 ,9w9:6 printf89enter te*t here 9:6 the sa e

scanf89Es9 , teRt:6 fputs8te*t,fp :6 fclose8 fp :6 fp 7 fopen89line. t*t9, 9r9:6 if8fgets8te*t,M-,fp :D7N$33: while8te*tOiP D7&1O&: { putchar8te*tOiS6 i<<6 } fclose8tp :6 getchO6 F *. fread8: and f!rite 8: f$nctions Tou can regard an array, or an array of structured variables, as simply a block of memory of a particular si)e. !he input#output routines provide you with routines that you can call to drop a chunk of memory onto a disk file with a single function call. Nowever, there is one thing you must remember. "f you want to store blocks of memory in this way the file must be opened as a binary file. hat you are doing is putting a piece of the program memory out on the disk. Tou do not Row how this memory is organised, and will never want to look at this, so you must open the file as a binary file. "f you want to print or read te*t you use the fprintf or scanf functions. !he function f!rite sends a block of memory out to the specified file. !o do this it needs to know three things6 where the memory starts, how much memory to send, and the file. to send the memory to. !he location ofthe memory is ;ust a simple pointer, the destination is a pointer to a FILE which has been opened previously, the amount of memory to send is given in two parts, the si)e of each chunk, and the number of chunks. !his might seem rather long w;nded, but is actually rather sensible. Consider: typedef struct G char name OH-P 6 char address OU-P 6 int account 6 int balance 6 int overdraft 6 F customer6

customer Null5,ranch O>--P 6 2"34 0 Null52ile6 fwrite 8 Null5,ranch, si)eof 8 customer:, > --, Null52ile: 6 !he first parameter to f!rite is the pointer to the base of the array of our customers. !he second parameter is the si)e of each block to save. e can use si+eof to find out the si)e of the structure. !he third parameter is the number of customer records to store, in this case >-and the .final parameter is the file which we have opened. Note that if we change the number of items in the customer structure this code will still work, because the amount of data saved changes as well. !he opposite off!rite is fread. !his works in e*actly the same way, but fetches data from the file and puts it into memory: fread 8 Null5,ranch, si)eof 8 customer:, > --, Null5'ata: 6 "f you want to check that things worked, these functions return the number of items that they transferred successfully: if8 fread 8Null5,ranch, si)eof8 customer:, >--, Null5'ata: B >--: G printf 8 9Not all data has been readD1n1n9 : 6 F F Sa ple progra $sing freadO and f!riteO f$nctions Aincl udeBstdio .hQ struct student { char nameO=-P6 int age6 FstudOMP6 void main8: G 2"34 0fp6 int i,;7-,n6 char strO>MP6 fp7fopen89line. t*t9 ,9rb9:6 printf89enter the number of records9:6 scanf89Ed9,n:6 for8i7O6iBn6i<< : { scanf89Es9,studOiP .name:6 scanf89Ed9,studOiP .age:6 }

whileVBn: { fwrite8 Istud,si)e8 stud:, > ,fp:6 ;<<6 } } fclose8fp :6 fp7fopen 89line. t*t9, 9r9:6 ;7-6 whileVBn: { fread8 Istud,si)eof8 stud:, > ,fp:6 printf89Es Ed9 ,studO;P .name,studO;P .age:6 F fclose8fp :6 F ,. Rando access files:

!he file "#O routines all work in the same way6 unless the user takes e*plicit steps to change the file position indicator, files will be read and written se/uentially. A read followed by a write followed by a read 8if the file was opened in a mode to permit that: will cause the second read to start immediately following the end of the data ;ust written. 8Remember that stdio insists on the user inserting a buffer.flushing operation between each element of a read. write.read cycle.: !o control this, the Random Access functions allow control over the implied read#write position in the file. !he file position indicator is moved without the need for a read or a write, and indicates the byte to be the sub;ect of the ne*t operation on the file. !hree types of function e*ist which allow the file position indicator to be. e*amined or changed. !heir declarations and description follow. Ainclude Bstdio.hQ #0 return file position indicator 0 # . long ftell82"34 0stream:6 int fgetpos82"34 0stream, fpos5t 0pos:6 #0 set file position indicator to )ero 0 # void rewind 82"34 0stream:6 #0 set file position indicator 0# int fseek82"34 0stream, long offset, int ptmame:6 int fsetpos82"34 0stream, const fpos5t 0pos:6 ftell returns the current value 8measured in characters: of the file position indicator if stream refers to a binary file. 2or a te*t file, a &magic& number is returned, which may only be used on a subse/uent call to fseek to reposition to the current file position indicator. On failure, .> 3 is returned and ermo is set. rewind sets the current file position indicator to the start of the file indicated by stream. !he file&s error indicator is reset by a call of rewind. No value is returned. 2seek allows the file position indicator for stream to be set to an arbitrary value 8for binary files:, or for te*t files, only to a position obtained from ftell, as follows:

"n the general case the file position indicator is set to offset bytes 8characters: from a point in the file determined by the value of ptrname. Offset may be negative. !he values of ptmame may be (44W5(4!, which sets the file position indicator relative to the beginning of the file, (44W5C$R, which sets the file position indicator relative to its current value, and (44W54N', which sets the file position indicator relative to the end of the file. !he latter is not necessarily guaranteed to work properly on binary streams. 2or te*t files, offset must either be )ero or a value returned from a previous call to ftell for the same stream, and the value ofptrname must be. (44W5(4!. 2seek clears the end of file indicator for the given stream and erases the memory of any ungetc. "t works for both input and output. Xero is returned for success, non.)ero for a forbidden re/uest.

Note that.for ftell and fseek it must be possible to encode the value of the file position indicator into a long. !his may not work for very long files, so the (tandard introduces fgetpos and fsetpos which have been specified in a way that removes the problem. fgetpos stores the current file position indicator for stream in the ob;ect pointed to by pos. !he value stored is &magic& and only used to return to the specified position for the same stream using fsetpos. fsetpos works as described above, also clearing the stream&s end.of.file indicator and forgetting the effects of any ungetc operations. 2or both functions, on suc,cess, )ero is returned6 on failure, non.)ero is returned and errno is set. OAincl$de Bstdio.hQ ; int ain"# { 2"34 * f6 f7 fopen89myfile.t*t9, 9w9:6 fputs89Nello (44W5(4!:6 fputs89 "ndia9, f:6 fclose8f:6 return -6 }

orld9, f:6 fseek8f, U,

-o! the file consist of follo!ing data: Nello "ndia (ample program to print the current position of the file pointer in the file using ftell8: function: AincludeBstdio.hQ . void mainO G 2"34 0fp6 char ch6 fp7fopenV&lines.t*t9 ,9r9:6 fseek8 fp,=> ,(44W5(4!:6 ch7fgetc8fp :6 clrscrO6 while8Dfeof8fp :: G printf89Ec9 ,ch:6 printf89Ed9,ftell8fp ::6 ch7fgetc8fp :6 } rewind8fp :6 while8D feof8 fp:: G printf89Ec9 ,ch:6 printf89Ed9 ,ftell8fp::6 ch7fgetc8fp :6 F fclose8fp :6 F 1. Error handling "t is possible that an en.or may occur during "#O operations on a file. !ypical en.or situations include: >. =. H. Y. M. U. !rying to read beyond the end of file mark. 'evice overflow !rying to use a file that has not been opened. Opening a file with an invalid file name. Attemting to write to a write protected file. !rying to perform an operation on a file when the file is opened for another type of operation. he standard "#O functions maintain two indicators with each open stream to show the end.of file and en.or status of the stream. !hese can be interr.ogated and set by the following functions: .

Ainclude Bstdio.hQ void clearerr82"34 0stream:6 int feof82"34 0stream:6 int ferror82"34 0stream:6 void perror8const char 0s:6 clearer clears the error and 4O2 indicators for the stream. feof: returns non.)ero if the stream&s 4O2 indicator is set, )ero otherwise. 2error: returns non.)ero if the stream&s error indicator is set, )ero otherwise. ?error: prints a single.line error message on the program&s standard output, prefi*ed by the string pointed to by s, with a colon and a space appended. !he error message is determined by the value of ermo and is intended to give some e*planation of the condition causing the error. 2or e*ample, this program produces the error message shown: Ainclude Bstdio.hQ Ainclude Bstdlib.hQ Zain8: G fclose8stdout:6 if8fgetc8stdout: Q7 -: { fprintf8stderr, 9 hat . no errorD1n9:6 e*it84%"! 52A"3$R4:6 } ferror89fgetc9:6 e*it84%"! 5($CC4((:6 F #0 Result 0# fgetc: ,ad file number

/ssign ent 0$estions and progra s: >. hat is the difference between end of a file and end of a string[ =. 'istinguish between te*t mode and binary mode operation of a file[ H. hat is the use of fseekO[ 4*plain its synta*[ Y. Now does an append mode differs from a write mode[ M. Compare between printf and fprintf functions[ U. hat is the significance of 4O2[ L. hat are the common uses of rewind and ftell functions[ \. 'escribe the use and limitations of the functions getc and putc[ ]. hat is the difference between the statements rewind8fp: and fseek8fp,O3,O:[ >-. rite a program to reposition the file to its lOth character[ >>. rite a program to find the si)e of the file[ >=. rite a program to write contents of one file in reverse into another file[ >H. rite a program to read to interchange the contents of two files[ >Y. rite a program to combine contents of two files in a third file[ >M. rite a program to read the contents of three files and find the largest file[ >U. rite a program to show how the rewind function works[ >L. rite a program to read the last few characters of the file using fseek function[ 1its: >. hich one of the following function is used for sorting information in a disk file O dP a: (canf8: b : fscanf 8: c :printf 8: d:fprintf8: =. !he 4O2 is e/uivalent to OcP a: = b: > c: .> d: -

H. hich of the following function is used to set the record pointer at the beginning of the file OcP a: ?utc8: b: getw8: c: rewind8: d: gets8: Y. a: hich of the following mode ope/s a binary file in write mode OdP < b:T wb< c: w d: wb

M. hich of the following functions used to write an entire block of data to a file OdP a: 2puts b:. fgets c: fscanf d: fwrite U. !he fscanf8: function reads data from OaP a: 2ile b: keyboard c: both a and b d: none L. hen fopen8: fails to open the file it returns OaP a: Null b: .> c: > d: none \. !he rewind function takes number of arguments OaP a: > b:= c:H d:Y ]. fseek8 fptr,-,-: is e/uivalent to ObP a: ftell b: rewind c: fput d: none

]. feof function checks for O cP a: fiKe opening error b: data error

c: end of file d: file closing error

>-. !he contents of the file are safe if it is opened in 5 mode O aP a: a b: r c: a<b d: none >>. !he general format of feof function OdP a: 2eof8fp,9 control string9: b:feof8fp: c: feof8fp,list: d: none >=. hich of the following is used to store data permanently OdP a: Arrays b: structures c: pointers d: files >H. !he file opened in w< mode can be OaP a: Read#write b: only read c: only write d: none >Y. !he fseek function needs 5 arguments ObP a: = b: H c: > d: none >M. hich of the standard file pointer is used for standard au*illary device ObP a: (tdpm b:stdau* c: stdio d: stdconio >U. hich of the following function is used to read each member of the structure in the fileOcP a: Vets b: puts c: fscanf d: fprintf >L. !he contents of the file is lost if it is opened in 55 mode ObP a: a b:w c:w< d:a< >\. !he function that is not used for random access to file OdP a: 2tell b: rewind c: fseek d:fprintf >]. !he C library that contains the prototype statement for the file operation ObP a: ?roto.h b: file.h c: stdio.h d: stdlib.h

rite a program to read last few characters of the file using fseek 8: (tatement. A include B stdio.hQ A include B conio.hQ Joid main 8: G 2ile 0 fp6 "nt n, ch6 Clrscr 8:6 2p7fopen 8^te*t.t*t_, ^r_:, ?rintf 8^#n contents of file 1n_:6 while 88ch7fgetc8fp::D74O2: ?rintf 8^Ec_, ch:6 ?rintf 8^#n Now many characters including spaces would you like to skip[:_:6 while 88ch 7 fgetc8fg::: printf 8^Ec_ch:6 fclose8fp:6 F o#p: Now many characters including spaces would you like to skip[ : M 3at characters of the file OR3'

S-ar putea să vă placă și