ANSI C provides a set of functions for reading and writing character by character or one byte at a time. These functions are defined in the standard library. They are listed and described below:
• getc()
• putc()
getc( ) is used to read a character from a file and putc( ) is used to write a character to a file. Their syntax is as follows:
int putc(int ch, FILE *stream);
int getc(FILE *stream);
The file pointer indicates the file to read from or write to. The character ch is formally called an integer in putc( ) function but only the low order byte is used. On success putc( ) returns a character(in integer form) written or EOF on failure. Similarly getc( ) returns an integer but only the low order byte is used. It returns EOF when end-of-file is reached. getc( ) and putc( ) are defined in as macros not functions.
fgetc() and fputc()
Apart from the above two macros, C also defines equivalent functions to read / write
characters from / to a file. These are:
int fgetc(FILE *stream);
int fputc(int c, FILE *stream);
To check the end of file, C includes the function feof( ) whose prototype is:
int feof(FILE *fp);
It returns 1 if end of file has been reached or 0 if not. The following code fragment
explains the use of these functions.
0 comments:
Post a Comment
Let us know your responses and feedback