Answer: We know that simplest I/O is individual characters I/O. getchar family of functions are used for reading single characters. These functions are prototyped below
int fgetc(FILE *); int getc(FILE *); int getchar(void);
Notice that fgetc() and getc() functions take desired stream as argument while getchar() always reads from stdin stream. Further, all functions read the next character from the input and return it as value of function. notice that though these functions are supposed to read characters but they return it as an integer. The main reason for returning a character as an integer is ‘EOF’ character that designates end-of-file. If there aren’t any more characters on the stream, they return ‘EOF’ instead. If any of 254 characters were used to mark end-of-file, then it would be impossible to read beyond that character as it would signal end-of-file. Having an integer as the return value solves the problem. Also, it makes it convenient to read all characters in binary file where all characters may occur as well as text file.
Similarly, writing out individual characters to output stream is accomplished by putchar family of functions. These are prototyped below,
int fputc(int ch, FILE *); int putc(int ch, FILE *); int putchar(int ch);
Notice that fputc() and putc() functions take character to be written and desired stream as arguments while putchar always writes to stdout. Notice further that these functions take character to be written as integer, then truncate integer to unsigned character before writing out to the file. For ex.
Notice that putchar() outputs to stdout a single character of multi-character character constant ‘uvw’ but which character is implementation dependent.
Functions fgetc(), fputc() are TRUE functions while getc(), putc(), getchar() and putchar() are #defined macros and therefore NOT TRUE functions. As we know macros are more efficient than true functions in terms of execution speed while true functions are more efficient in terms of program size. We have a choice to use either according to situation. This distinction is rarely a matter of concern because differences observed in programs using one or the other is not significant.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.