Sie sind auf Seite 1von 7

Chapter 9

Files in C
Let us get down to business right away. To operate on files you will first have to, as in any other language, open a file. When you open a file, you will have to specify what kind of operation you desire on the file. This is achieved by opening the file in a specific mode. The different modes of opening a file allow you to read from, write to append to and update the contents of the file. One of the first points that we shall make is this: to operate on files you need to declare a F L!" variable. What is a F L! pointer# $ery simply put it is a pointer to a F L!. That brings us to the ne%t &uestion: What is a F L!# ' F L! is a data type (defined in stdio.h) which is used to operate on files. *ince you may open several files simultaneously, when you want to perform +O on a file you will need some means to identify and specify which file you want to operate on. This is the purpose the F L! pointer variable serves. ,ou will pass the F L! pointer as a parameter to the +O functions thereby identifying the files to operate on. To open a file, the stdio library provides function called fopen. The prototype of the function fopen is shown below:

F L! " fopen (char " filename, char " mode)'s you can see, the function e%pects two parameters: the first one, which is a character pointer is e%pected to be pointing to a sting containing the name of the file to be opened. *ince you are aware that the name of a char array is a pointer to the array, as well as, a &uoted string constant, is a char pointer, the first parameter can be either of these. Look at the e%amples shown below. 'll of them are legal calls to fopen. char " fname . / +etc+passwd0char filename 1234 . /+etc+passwd0F L! " fpl, " fp2, "fp5- + " 6ot F L! " fpl, fp2, fp5-7 "+ fp8 . fopen (fname, /r0)fp2 . fopen (filename, /r0 )fp5 . fopen ( /+etc+passwd0, /r0)6ote that the file name can be either an absolute path name or a relative path name. Whether or not the file names are case sensitive is operating system dependent. The second parameter to fopen is a char pointer, pointing to a string containing the mode of opening. The table given below, lists the important modes and their significance. Turn to the reference section for a detailed discussion of the other modes.
9opyright Logic Option :vt. Ltd. 8

TABLE
*.6o. 8 2 ;ode /r0 /w0 'ccess >ead only- File must be present and readable- soon after opening current position is set to top of file Overwrite. f file present contents are discarded. f file is absent it gets created. !ssentially a rewrite mode. 'ppend. f file present any output done gets appended. f file absent it gets created. 's soon as file is opened current position is set to the end of file. ?pdate. File must be present. >ead as well write access available. 9urrent position as soon as fopen is called is top of file.

5 <

/a0 /r=0

The function fopen, tries to open the said file in the said mode and if successful, returns a F L! pointer, which you will capture in you own F L! " variable. 6ote that, if you fail to capture the return value of fopen, you cannot access the file. f fopen encounters an error, it returns a 6?LL pointer. ,ou should never assume that a file open operation will be successful. ,ou must always check for errors and if they do occur, act suitably. We have earlier discussed the dangers of indifferencing a 6?LL pointer. 9onsiderations such as those necessitate good error trapping and error handling. Why should fopen fail at all# This could be because of a number of reasons: 8. When you are trying to open a file in read mode, the file must be present. Trying to take input from a non@e%istent file, is meaningless and therefore will result in an error. t could be that, the file is present but you do not have the necessary access right. f the mode of opening employed is /w0 and the file not present, fopen tries to create a file by that name. For this operation to be successful you need write permission on the target directory and if this is not available fopen will fail.

2. 5.

9opyright Logic Option :vt. Ltd.

<. A.

!very O* imposes a ma%imum limitation on the number of files that can be open simultaneously. This limit is 23 for ?ni%. ?nder ?ni%, directories can be opened as though they were files. 6ote that you can open a directory, only in read mode, and cannot open it in any output mode even if write permission is available on that directory. 'n absolute path name is specified and some component of the path is missing.

B.

' number of points re&uire attention here. Once a file is successfully opened, you can perform +O on the file based on the opening mode. t goes without saying that a file opened is /w0, and the file is present, the fileCs content are discarded and the file is created afresh. The append mode /a0, allows you to add on to the file, without destroying its original contents. The /a0 mode also creates a file it is not present.

CHARACTER I/O
9 provides a number of functions to perform character +O on files. getc can be used to read a character from an open file. The prototype of getc is as shown below: int getc (F L! " fp)getc is functionally very similar to getchar. t reads a character from the file specified and returns an int containing the value read. On end of file, getc too returns !OF. putc, which is the twin of getc, performs character output on files and has the prototype shown below: int putc (int ch, F L! " fp) putc writes the given character to the given file and on success, returns the same character. putc returns !OF on error. f this happens, the possible reason could be a disk@full condition. Let us put into practice the skills ac&uired to write a program now: a program which will copy one file to another. Dinclude E stdio.hF main (int argc, char " argv1 4 ) G F L! "fpl, "fp2int chif ( argc 7. 5) G putc(/?sage : copy sourceHfile targetHfile0)e%it (8)I
9opyright Logic Option :vt. Ltd. 5

fp8 . fopen (argv184, /r0)if (fp8 .. 6?LL) G printf (/9annot open source fileJn0)e%it (2)I if ( ( fp2 . fopen (argv124, /w0)) . . 6?LL) G printf(9annot open target fileJn0)e%it (5)I while ( (ch . getc (fp8 )) 7 . !OF) G if (putc ( ch, fp2) 7 . ch) G printf (/!rror writing target file Jn0)e%it (<)I I + " end of while loop " + fclose (fp8)fclose (fp2)+" fclose (fp8, fp2) not allowed7 "+ e%it (3)I 6ote that, with file +O there is always a notion of current position. The current position specifies where in the file your ne%t input or output operation will take place. The different modes of opening of files leave the current position in different places, as you saw in table. *o when in the above program, the source file is opened in read mode the current position is set to the top of file. Thus when the program calls getc for the first time what it reads is in fact the very first character in the file. 's soon as getc reads the first character the current position has changed to the subse&uent byte, so that a subse&uent call to getc returns the ne%t byte in the file. Kence the name se&uential access. The program itself is simple and deserve little discussion. *o, let us look at the function fclose, instead. The function fclose, is used to close a file. The file to be closed will be identified by passing the associated F L! pointer. Once a file is closed, you have lost access to it and unless it is reopened you cannot operate on it. 'll files that you open in your program, must be closed by you. Failing to close a file may result in problems like, loss of data, files not being updated properly and so on. 6ote that fclose returns !OF on error. 9 provides yet another pair of functions to perform character +O. The function fgetc, is for all practical purposes, identical in its nature to getc. t accepts the same parameters perform the same task and returns the same values as getc does. *imilarly, the function fputc, is &uite identical to putc in all respects. *o, what is the difference between these pairs of functions at all# Letc and putc are, often, implemented as macros, while fgetc and fputc are pure functions. ;acros will be the subMect of discussion in a later chapter. For the moment, we shall close this discussion by saying that these pairs of functions are operationally identical but differ in the way they have been implemented.
9opyright Logic Option :vt. Ltd. <

STRING I / O
Kaving Niscovered how to carry out character +O, let us now turn our attention to string +O. The pair of functions fgets and fputs allow you to read and write strings to files. The prototype of these functions are provided below: 9har " fgets ( char " buffer, unsigned ma%Hchars, F L! " fp)nt fputs (char " buffer, F L! " fp)The function fgets, which is similar to gets, as you can observe, takes 5 parameters. The first parameter is the pointer to the destination buffer. fgets reads either until a OJnC is encountered or ma%Hchars@8 number of characters have been read already, whichever occurs earlier. 6ote that, fgets transfers the OJnC also to the buffer, as against gets, which does not. The function fputs, prints the specified string onto the given file, fputs does not issue a termination OJnC, automatically. 's we already discussed, the 9 stdio functions, behave in a specific way, when they encounter an error or an anomalous condition. ,ou can in general observe that the pointer returning functions, return 6?LL pointer on error, while the int returning functions, return !OF on error, Though this is not a rule, it is a commonly followed practice. Think of such pointer functions as malloc, calloc and fopen: all of these return 6?LL pointer on error. On the other hand, getchar, getc and fgetc, return !OF on error. True to this spirit, the function fgets returns a 6?LL pointer on error while fputs returns !OF. Let us now write a program which will show how the head command of ?ni% can be implemented. D include Estdio.hF D include Estdlib.hF D define * P! 833 main (int argc, char " argv 1 4) G int countF L! "fp9har buffer 1 * P! 4if (argc7 .5) G puts (/?sage: head number filename0)e%it (8)I count . atoi (argv184+"convert string to binary int "+ if ( ( fp=fopen (argv 124, /r0)) . . 6?LL) G
9opyright Logic Option :vt. Ltd. A

perror(argv 1 2 4 ): e%it ( 2 )I while (fgets (buffer, * P!, fp) 7. 6?LL Q Q count F 3) G printf (/ Rs0, buffer)count@@I fclose (fp) e%it (3)I *ince the number of lines to be displayed, as supplied in the command line, is a null terminated '*9 string and not a binary int, it has to be converted before usage. The function atoi achieves this. t accepts a string and returns the e&uivalent binary int. 6ote that the 9 library also provides other functions such as atof ('*9 @to@float) and atol ('*9 @to@long). We saw earlier that there could be several reasons for fopen to fail. This is true, not only of fopen but also of several other functions. *o, how are we to determine the actual cause of failure of a function# The function perror (short of print error) helps you do this. perror accepts one parameter S a character pointer. t prints whatever is passed to it, followed by a diagnostic message which tells you the e%act cause of the error. What do imagine is the significance of the parameter to perror# To perform formatted +O on files, 9 library provides two functions, namely fprintf and fscanf. Their prototypes are given below: int fprintf (F L! " fp, char " formatHstring, T. )int fscanf ( F L! " fp, char " formatHstring, T. )These functions are &uite similar to their studio counterparts, printf and scanf, e%cepting that these operate on files, while those operate on the standard +O streams. 'ccordingly, these functions receive as the first parameter, the F L! pointer indicating the file on which +O is to be done.

ERROR HANDLING
>eflect for a moment on how the above programs handle errors. Uoth the copy and head programs use the function perror to print a diagnostic message and e%it when the file open fails. Though this kind of error handling is perfectly all right for the above programs, it is not suitable for all programs. For e%ample if a word@processor finds that the file specified is missing, it Must cannot e%it after printing a message. t has to ask the user if he + she wants to create a fresh one and act according to the userCs wishes. *o how to handle this kind of a situation at all#

9opyright Logic Option :vt. Ltd.

The 9 library functions, when they encounter an error, set a variable errno (for error number). The variable errno is an integer declared in the file errno.h. The 9 library functions deposit different values in the variable errno for different kinds of errors. When a program encounters an error it can inspect the value available in the variable errno and based on this decide on a suitable course of action. Typical values deposited in errno for various important error conditions are shown in table below. 6ote that identifiers used, are all symbolic constants defined in errno.h and such being the case, a program will have to include the file errno.h to use these constants. errno value !'99!* !6O!6T !6O;!; !6O*:9 !;F L! eanin! 'ccess denied 6o such file or directory 6o room in >'; Nisk full Too many open files

6ote : The variable errno is set only when errors occur and is not cleared by the library functions when they are successful. *o the value is meaningful only immediately after an error. When an error occurs, the program should try to transmit error messages to the standard error device rather than to the standard output. This is to ensure that the output message, which is meant for the userCs inspection, does not get redirected to a file or drain down in a pipeline. The stdio.h header file, introduces three F L! pointer constants, namely stdin, stdout and stderr. Uear in mind that these are not variables. These F L! pointer constants point to the standard input, standard output and standard error device, respectively. These can be used in any place where a F L! pointer is re&uired. Look at the following code fragments: getc ( stdin)fprintf ( stderr, /file missing0)fputs ( /Kello 7 Jn0, stdout )+ " e&uivalent to getchar() " + + " O + : goes to $N? even under redirection " + + " *ame a puts (/ Kello 7 /)- " +

The stderr F L! pointer is particularly useful with respect to error handling and can be used as shown above

9opyright Logic Option :vt. Ltd.

Das könnte Ihnen auch gefallen