Your browser doesn't support JavaScript Input and Output – Windows Programming

Input and Output

In C, input sources and output destinations are collectively known as devices. Examples of devices include the keyboard, screen, printer, and disk files.

All input and output operations in C are performed through streams. A stream is a device-independent flow of data represented as a sequence of bytes. A sequence of bytes flowing into a program is called an input stream, while a sequence of bytes flowing out of a program is called an output stream.

Each stream is associated with a file. In C, the term file refers not only to data stored on disk, but also to devices such as the keyboard, screen, and printers. This file abstraction provides an intermediate layer between the program and the actual physical device used for input or output.

By treating all input and output devices as files, C provides a uniform and portable method of performing input and output operations.

Text Versus Binary Streams

C streams can be either text streams or binary streams.

Text streams are organised as a sequence of characters, typically divided into lines and terminated by a newline character. Certain characters in a text stream have special meanings and may be translated by the C implementation to conform to the conventions of the host environment. For example, the representation of a newline may differ between operating systems.

In contrast, a binary stream can contain any type of data. The bytes in a binary stream are not interpreted or translated by the C implementation in the same way as they may be in a text stream. Binary streams are therefore generally most useful for storing and processing non-textual data, such as images, audio, and other files containing binary data.

Predefined Streams

The ANSI standard for C has three predefined streams –

typename
Standard inputstdin
Standard outputstdout
Standard errorstderr

C’s Stream Functions

The C standard library provides a variety of functions that allow programs to perform input and output operations. These library functions allow a program to read from and write to streams.

Unformatted Output with putchar(), putc(), fputc(), puts(), and fputs()

Unformatted I/O transfers characters or strings without the formatting and conversion performed by formatted I/O functions such as printf(). These functions provide a simple and efficient way of performing basic input and output operations.

putchar()

The putchar() function writes a character to the standard output stream(stdout). The prototype for putchar is as follows:

putchar(int ch);

The value parameter ch may be a type char or type int thus a value of int c=89 or char c=’Y’ will produce the same output.

putc()

The putc() function writes a single character to a specified output stream.

The prototype for putc() is:

int putc(int ch, FILE *stream);

The first argument is the character to be written, and the second argument specifies the output stream.

fputc()

The fputc() function also writes a single character to a specified output stream.

The prototype for fputc() is:

int fputc(int ch, FILE *stream);

putc() and fputc() perform essentially the same operation. The main difference is that putc() may be implemented as a macro, whereas fputc() is a function.

puts()

The puts() function writes a string str and a trailing newline to stream stdout. The prototype for this function is

puts(char* str)

where str is the C string to be written

fputs()

The fputs() function writes a null-terminated string to a specified output stream. Unlike puts(), fputs() does not automatically append a newline character. The prototype for fputs is as follows

int fputs(const char *str, FILE *stream)

The fput function takes two arguments: the first is the string to be written to the file and the second is the stream where the string will be written.

The code section below demonstrates the use of putchar(), putc(), fputc(), puts(), and fputs()-

#include <stdio.h>

int main()
{
    int c = 89;
    char str[] = "hello world";
    putchar(c);          // writes the character Y (ASCII 89) to stdout.
    putchar('\n');       // writes a newline to stdout.
    putchar('Y');        // writes the character Y to stdout.
    putchar('\n');       // writes a newline to stdout.
    putc('Y', stdout);   // writes the character Y to stdout.
    putc('\n', stdout);  // writes a newline to stdout.
    fputc('Y', stdout);  // writes the character Y to stdout.
    fputc('\n', stdout); // writes a newline to stdout.
    puts(str);           // writes the string str followed by a newline to stdout.
    fputs(str, stdout);  // writes the string str to stdout without a newline.
    putchar('\n');       // writes a newline to stdout.

    return 0;
}

Unformatted input with fgets() and getchar()

getchar

The getchar() function reads a single character from the standard input stream (stdin) and returns it as an int. It can be used in a loop to read more than one character. The short program below demonstrates the use of getchar() by asking the user to enter a character and then echoing the character to the screen.

#include <stdio.h>
int main( )
{
int c;
printf("Enter a character followed by return ");
c = getchar();//prompts for screen input store ascii code of character
putchar(c);//writes character to stdout
}

fgets()

The fgets() function reads a specified number of characters from the input stream and stores it in a string. The prototype of fgets() is

fgets(string,size,stdin);

Here string is the name of a char array, size is the amount of text to input plus one (this must be no larger than the size of the char array), and stdin is the name of the standard input device, as defined in the stdio.h header file. 

The short program below demonstrates the use of the fgets() by asking the user to enter a string and then echoing the string to the screen.

#include<stdio.h>
int main()
{
char str[100];//declared character array of length 100 
printf("Enter a string followed by enter ");
fgets(str,100,stdin);//stores user input in chr array str
puts( str );//writes str to stdout
}

In this example, str can hold up to 99 characters of input, plus the terminating null character ('\0').

Formatted Input and output with the scanf() & printf() functions

Formatted I/O allows data to be converted between its textual representation and the internal data types used by a C program. It is designed to produce and process human-readable text. The conversion and formatting performed by these functions requires additional processing compared with unformatted I/O.

scanf 

Is a function that reads and stores formatted data from the standard input stream stdin. The prototype for scanf is

int scanf ( const char * format, ... );

Scanf() accepts a variable number of arguments but requires a minimum of two. The first argument is a format string that uses special characters to indicate how to interpret the input data. The second, and remaining arguments, are the addresses of the variable(s) to which the input data is assigned. 

printf 

Is a function that writes formatted data to the standard output stream stdout. The printf() function is part of the standard C library and is complementary to scanf.  The prototype for printf is

int printf ( const char * format, ... );

The printf() function can accept a variable number of arguments but requires a minimum of one.  The format string contains the text to be written to stdout and optional embedded format tags. These optional parameters are variables and expressions which describe further output formatting information. 

The following code shows the usage of both printf and scanf. When the code is compiled, it will ask the user to enter a name and age separated by a space. When a value is entered, it will be displayed on the screen.  The purpose of %d inside the scanf() and printf() functions is to provide string formatting information. 

#include<stdio.h>
int main()
{
 char name[20];
 int age;
 printf("Please enter your name & age - ");
 scanf("%20s %d", name,&age);//prompts for input max 20 characters and value.stores data in name and age
 printf( "Hello: %s %d years old", name,age);//writes name and age to stdout
}

some of the more common format parameters 

Format String Meaning
%d signed decimal number
%f floating point number
%u  decimal
%i integer as a signed number.
%c character
%s character string. The scanning ends at whitespace.
 %g%G floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses upper-case.
 %x, %X hexadecimal number. %x uses lower-case letters and %Xuses upper-case.
 %o Scan an integer as an octal number.

It is also possible to limit the number of digits or characters that can be input or output, by adding a number with the format string specifier such as “%1d” or “%4s“. The first specifier indicates a single numeric digit and the second specifier indicates 4 characters. Entering 99, while scanf() has “%1d”, means only one digit will be accepted regardless of how many digits are entered.