Exforsys

Home arrow Technical Training arrow C Tutorials

C Programming - Managing Input and Output Operations

Page 1 of 3
Author:      Published on: 30th Mar 2006    |   Last Updated on: 16th Aug 2011

Input Output operations are useful for program that interact with user, take input from the user and print messages. The standard library for input output operations used in C is stdlib. When working with input and output in C there are two important streams: standard input and standard output. Standard input or stdin is a data stream for taking input from devices such as the keyboard. Standard output or stdout is a data stream for sending output to a device such as a monitor console.

Ads

To use input and output functionality in your program, you need to include stdio header:

Sample Code
  1. #include <stdio.h>
Copyright exforsys.com


Single Character Input and Output

getc is used to accept a character from standard input and is declared as follows:

Sample Code
  1. int getc(FILE *stream);
Copyright exforsys.com


You would pass stdin for the stream to get input from the command line. getchar also has the same definition as getc.  It is equivalent to getc with stdin as its argument.

Sample Code
  1. getc(stdin);
Copyright exforsys.com


fgetc function is recommended for accepting a single character from standard input and is declared as follows:

Sample Code
  1. int fgetc(FILE *stream);
Copyright exforsys.com


If the call to fgetc is successful it returns char, otherwise it will return EOF (End of File).

putc is used for sending a single character to standard output and is defined as follows:

Sample Code
  1. int putc(int c, FILE *stream);
Copyright exforsys.com


fputc function is recommended instead of putc. fputc syntax is shown here below:

Sample Code
  1. int fputc(int c, FILE *stream);
Copyright exforsys.com


Below example demonstrates fgetc and fputc functions.

Ads

When fputc is successful, it will return the value, if it fails it will return EOF.

getachar.c:

Sample Code
  1. #include <stdio.h>
  2. void main() {
  3. char ip;
  4. //prompt for character and get input.
  5. printf("Type a character and press enter.n");
  6. ip = fgetc(stdin);
  7. //write input value back out to standard out.
  8. fputc(ip, stdout);
  9. printf("n");
  10. }
Copyright exforsys.com


Here is the output I got when typing "a" for my character:




 
This tutorial is part of a C Tutorials tutorial series. Read it from the beginning and learn yourself.

C Tutorials

 

Comments