ch8-getchar() with read(), write()
Chapter_8 copy | cp_(copy_files) Exercise_8-1 |
getchar.c K&R, p. 171-172 download
#include <stdio.h> // for BUFSIZ, EOF
#include <unistd.h> // for read(), write(), fd 0 (stdin), 1 (stdout)
int getchar1(void); // read one char at a time
int getchar2(void); // buffer version
int main() // copy input to output
{
int c;
while ((c = getchar1()) != '\n' && c != EOF)
{write(1, &c, 1);}
// write to 1 (stdout) 1 byte (second 1) from &c
write(1, &c, 1); // '\n' or EOF
while ((c = getchar2()) != '\n' && c != EOF)
{write(1, &c, 1);}
write(1, &c, 1); // '\n' or EOF
return 0;
}
int getchar1(void) // read one char at a time
{
char c;
// read from 0 (stdin) 1 byte into &c
return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;
}
int getchar2(void) // buffer version
{
static char buf[BUFSIZ]; // 8192 bytes
static char *bufp = buf; // initialize
static int n = 0; // initialize
if (n == 0) // static var n keeps its value
{ // from one function call to the other
n = read(0, buf, sizeof buf); // read from stdin (fd 0)
bufp = buf; // reset
}
// bufp keeps its incremented value until it is reset
return (--n >= 0) ? (unsigned char) *bufp++ : EOF;
} // when bufp reaches the end of buf[], n reaches 0
/*
gcc getchar.c -o getchar
./getchar
Hello! // Enter
Hello!
Goodbye! // Enter
Goodbye!
./getchar < getchar.c // write 2 lines
*/
Chapter_8 copy | BACK_TO_TOP | cp_(copy_files) Exercise_8-1 |
Comments
Post a Comment