Friday, January 6, 2012

file io in c

file io in c
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.

The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).

Thus the statement

c = getc(fp);

reads the next character from the file referenced by fp and the statement

putc(c,fp);

writes the character c into file referenced by fp. 

A simple example has been presented for displaying the file content.
/*
 */
In this program, we open the file ccplusplus.com for reading.

We then read a character from the file. This file must exist for this program to work.

If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of file has been reached. (Normally -1 is used for EOF). The while loop simply keeps reading characters from the file and displaying them, until the end of the file is reached. The function fclose is used to close the file i.e. indicate that we are finished processing this file. We could reuse the file pointer fp by opening another file.This program is in effect a special purpose cat command. It displays file contents on the screen, but only for a file called ccplusplus.com. By allowing the user enter a file name, which would be stored in a string, we can modify the above to make it an interactive cat command:
/*
 */
In this program, we pass the name of the file to be opened which is stored in the array called filename, to the fopen function. In general, anywhere a string constant such as “ccplusplus.com” can be used so can a character array such as filename. (Note the reverse is not true). The above programs suffer a major limitation. They do not check whether the files to be used exist or not. If you attempt to read from an non-existent file, your program will crash!! 

The fopen function was designed to cope with this eventuality. It checks if the file can be opened appropriately. If the file cannot be opened, it returns a NULL pointer. Thus by checking the file pointer returned by fopen, you can determine if the file was opened correctly and take appropriate action e.g.
 
fp = fopen (filename, "r") ;
 
if ( fp  ==  NULL)
{
   printf("Cannot open %s for reading \n", filename );
   exit(1) ; /*Terminate program: Commit suicide !!*/
}
 
The above code fragment show how a program might check if a file could be opened appropriately. The function exit() is a special function which terminates your program immediately.
exit(0) mean that you wish to indicate that your program terminated successfully whereas a nonzero value means that your program is terminating due to an error condition. Alternatively, you could prompt the user to enter the filename again, and try to open it again: 

fp = fopen (fname, "r") ;
 
while ( fp  ==  NULL)
{
   printf("Cannot open %s for reading \n", fname ); 
   printf("\n\nEnter filename :" );
   gets( fname );
   fp = fopen (fname, "r") ;
}

In this code fragment, we keep reading filenames from the user until a valid existing filename is entered.

Exercise:  Modify the above code fragment to allow the user 3 chances to enter a valid filename. If a valid file name is not entered after 3 chances, terminate the program.

RULE: Always check when opening files, that fopen succeeds in opening the files appropriately.
 
Obeying this simple rule will save you much heartache.
 
Example 1: Write a program to count the number of lines and characters in a file.
 
Note: Each line of input from a file or keyboard will be terminated by the newline character ‘\n’. Thus by counting newlines we know how many lines there are in our input.

/*
 */


Example 2: Write a program to display  file contents 20 lines at a time. The program pauses after displaying 20 lines until the user presses either Q to quit or Return to display the next 20 lines. (The Unix operating system has a command called more to do this ) 

As in previous programs, we read the filename from user and open it appropriately. We then process the file: read character from file while not end of file and not finished do 

begin
display character 
if character is newline then
linecount = linecount + 1; 
if linecount == 20 then
begin
linecount = 1 ;
Prompt user and get reply;
end
read next character from file
end 

/* 
 */

The string reply will contain the users response. The first character of this will be reply[0]. We check if this is ‘q’ or ‘Q’. The brackets [] in printf are used to distinguish the programs message from the file contents.


Example 3: Write a program to compare two files specified by the user, displaying a message indicating whether the files are identical or different. 

This is the basis of a compare command provided by most operating systems. Here our file processing loop is as follows:
read character ca from file A;
read character cb from file B;

while ca == cb and not EOF file A and not EOF file B
begin
read character ca from file A;
read character cb from file B;
end

if ca == cb then
printout(“Files identical”);
else
printout(“Files differ”);

This program illustrates the use of I/O with two files. In general you can manipulate up to 20 files, but for most purposes not more than 4 files would be used. All of these examples illustrate the usefulness of processing files character by character. As you can see a number of Operating System programs such as compare, type, more, copy can be easily written using character I/O. These programs are normally called system programs as they come with the operating system. The important point to note is that these programs are in no way special. They are no different in nature than any of the programs we have constructed so far.
/* 
 */ 


Writing to File:

The previous programs have opened files for reading and read characters from them. To write to a file, the file must be opened for writing e.g.

fp = fopen( fname, "w" );

If the file does not exist already, it will be created.  If the file does exist, it will be overwritten!  So, be careful when opening files for writing, in case you destroy a file unintentionally. Opening files for writing can also fail. If you try to create a file in another users directory where you do not have access you will not be allowed and fopen will fail.

Character Output to File:

The function putc( c, fp ) writes a character to the file associated with the file pointer fp.

Example: Write a file copy program which copies the file “ccplusplus.com” to “prog.old” 
 
Outline solution:

Open files appropriately
Check open succeeded
Read characters from ccplusplus.com and
Write characters to prog.old until all characters  copied
Close files
The step: Read characters .... and write ..” may be refined to:

read character from ccplusplus.com
while not end of file do
begin
write character to prog.old
read next character from ccplusplus.com
end

/* 
 */ 
The above program only copies the specific file ccplusplus.com to the file prog.old. We can make it a general purpose program by prompting the user for the files to be copied and opening them appropriately

/* 
 */  

No comments:

Post a Comment