Using stdin and stdout is trivially simple. Input and output occur one line at a time;
users type input using the keyboard or pipe input in from a file, and output is displayed to the
screen or redirected to a file. Listing 28-2 shows such a program, readkey.c.
LISTING 28-2
Reading and Writing to stdin and stdout
/*
* readkey.c - reads characters from stdin
*/
#include
int main(int argc, char *argv[])
{
int c, i = 0;
/* read characters until newline read */
printf("INPUT: ");
while ((c = getchar()) != '\n') {
++i;
putchar(c);
}
printf("\ncharacters read: %d\n", i + 1);
return 0;
}
765
Programming Environments and Interfaces 28
In this program, the ++i syntax is used to increment the variable i by one each time through the
while loop.
To compile this program, use the following command:
$ gcc readkey.c -o readkey
In the preceding code listing, readkey.c reads input from stdin until it encounters a newline
(which is generated when you press the Enter key). Then it displays the text entered and the number
of characters read (the count includes the newline) and exits.
Here??™s how it works:
$ ./readkey
INPUT: There are three primary means of creating programs that interact with
users at the command line
There are three primary means of creating programs that interact with users at
the command line
characters read: 96
The text wraps oddly because of this book??™s formatting constraints.
Pages:
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394