This chapter introduces buffered and unbuffered input, redirecting input and output streams, and ways to create a friendlier user interface. The objectives important to this chapter include:
Concepts:The single character macros, getchar() and putchar() perform input and output one character at a time. The putchar() macro is used to echo the input (a single character) on the terminal screen. Echoing of characters is an instance of unbuffered or direct input. In contrast, delayed echoing is associated with buffered input. A buffer is a temporary storage area where typed characters are collected until they are ready to be displayed. Buffering can be fully-buffered or line-buffered. Full buffering flushes a buffer area when the buffer becomes full. This type of buffering is associated with file I/O. Line buffering flushes the buffer when a newline character is found. Keyboard input illustrates line buffering. A file is an area of memory in which information is stored. C uses low-level and standard-package I/O in working with files. Low-level I/O functions are machine dependent (based on the host operating system). Standard package I/O functions provide a standard set of routines for working with I/O. The end of a file is identified by an EOF (end-of-file) marker. This marker is defined and stored in the stdio.h header file. Several points should be remembered when working with, getchar(), putchar(), and EOF.
File input and output and be redirected by adding a redirection operator to an executable C program. Commands using redirection are entered at the system command line, not in the C program itself. The format executable_program_file < text_file runs a C program, and uses input stored in the text file. The format executable_program_file < text_file1 > text_file2 takes input from text_file1 and saves its output as text_file2. C provides many tools to make writing the user interface an easier task. It provides functions such as getchar() to get a single character and scanf() to get a single number or string. There is a potential problem when mixing getchar() and scanf(). The function scanf() leaves a newline character in the input. If a getchar() follows scanf(), this newline character will be read by getchar() unless the programmer uses an if statement, or other such code, to work around it. A standard technique to clear out the input stream is to follow the call to scanf() with a call to fflush(). The format is: fflush(stdin); where fflush() is the name of a function that flushes buffers, and stdin is the name of the standard input stream. |