Monday, January 26, 2009

Simple I/O -- getchar, putchar, printf

main( )
{
char c;
c = getchar( );
putchar(c);
}

getchar and putchar are the basic I/O library functions in C. getchar fetches one character from the standard input (usually the terminal) each time it is called, and returns that character as the value of the function. When it reaches the end of whatever file it is reading, thereafter it returns the character represented by `\0' (ascii NUL, which has value zero). We will see how to use this very shortly.
putchar puts one character out on the standard output (usually the terminal) each time it is called. So the program above reads one character and writes it back out. By itself, this isn't very interesting, but observe that if we put a loop around this, and add a test for end of file, we have a complete program for copying one file to another.
printf is a more complicated function for producing formatted output. We will talk about only the simplest use of it. Basically, printf uses its first argument as formatting information, and any successive arguments as variables to be output. Thus
printf ("hello, world\n");
is the simplest use. The string ``hello, world\n'' is printed out. No formatting information, no variables, so the string is dumped out verbatim. The newline is necessary to put this out on a line by itself. (The construction
"hello, world\n"
is really an array of chars. More about this shortly.)
More complicated, if sum is 6,
printf ("sum is %d\n", sum);
prints
sum is 6
Within the first argument of printf, the characters ``%d'' signify that the next argument in the argument list is to be printed as a base 10 number.
Other useful formatting commands are ``%c'' to print out a single character, ``%s'' to print out an entire string, and ``%o'' to print a number as octal instead of decimal (no leading zero). For example,
n = 511;
printf ("What is the value of %d in octal?", n);
printf ("%s! %d decimal is %o octal\n", "Right", n, n);
prints
What is the value of 511 in octal? Right! 511 decimal
is 777 octal
Notice that there is no newline at the end of the first output line. Successive calls to printf (and/or putchar, for that matter) simply put out characters. No newlines are printed unless you ask for them. Similarly, on input, characters are read one at a time as you ask for them. Each line is generally terminated by a newline (\n), but there is otherwise no concept of record.

No comments:

Post a Comment