Standard Input And Output In C

Photo by RetroSupply on Unsplash

Standard Input And Output In C

About C

Input and output facilities are not part of the C language itself, So we use some standard library for the input and output facilities in our program. Here <stdio.h>

Standard Input Using getchar:

The simplest input mechanism is to read one character at a time from the standard input, normally the keyboard, with getchar:

int getchar(void)

getchar returns the next input character each time it is called, or EOF when it encounters end of file.

Substituting a file for the keyboard

A file may be substituted for the keyboard by using the < convention for input redirection: If a program prog uses getchar, then the command line:

prog <infile

causes prog to read characters from infile instead.

Input from the Output of another program

Input switching is also from other program via a pipe mechanism

otherprog | prog

runs the two programs otherprog and prog and pipe the standard ouput of otherprog into the standard input for prog

Standard Output Using putchar:

The function

int putchar(void)

is used for output: putchar() puts the character on the standard output which is default the screen. putchar() returns the character written, or EOF if an error occurs.

Output to a file

Output can usually be directed to a file with >filename if prog uses putchar:

prog >outfile

will write the standard output to outfile instead.