Friday, November 4, 2011

Standard I/O Devices in C programming language

To perform reading or writing operations on a file we need to use the function fopen( ), which sets up a file pointer to refer to this file. Most OSs also predefine pointers for three standard files. To access these pointers we need not use fopen( ). These standard file pointers are shown in Figure

Thus the statement ch = fgetc ( stdin ) would read a character from the keyboard rather than from a file. We can use this statement without any need to use fopen( ) or fclose( ) function calls.
Note that under MS-DOS two more standard file pointers are available—stdprn and stdaux. They stand for standard printing device and standard auxiliary device (serial port). The following program shows how to use the standard file pointers. It reads a file from the disk and prints it on the printer.
/* Prints file contents on printer */

#include "stdio.h"
main( )
{
FILE *fp ;
char ch
fp = fopen ( "poem.txt", "r" ) ;
if ( fp == NULL )
{
printf ( "Cannot open file" ) ;
exit( ) ;
}
while ( ( ch = fgetc ( fp ) ) != EOF )
fputc ( ch, stdprn ) ;
fclose ( fp ) ;
}

The statement fputc ( ch, stdprn ) writes a character read from the file to the printer. Note that although we opened the file on the disk we didn’t open stdprn, the printer. Standard files and their use in redirection have been dealt with in more details in the next section.
Note that these standard file pointers have been defined in the file “stdio.h”. Therefore, it is necessary to include this file in the program that uses these standard file pointers.


No comments:

Post a Comment