diff --git a/peek/peek.c b/peek/peek.c index 1bfb7bf..9150c61 100644 --- a/peek/peek.c +++ b/peek/peek.c @@ -1,5 +1,6 @@ #include /* errno */ -#include /* fprintf(3), getc(3), putc(3), EOF, NULL */ +#include /* fprintf(3), getc(3), putc(3), stderr, stdin, stdout, EOF, + * NULL */ #include /* size_t */ #include /* strerror(3) */ #if !defined EX_OK || !defined EX_OSERR || !defined EX_USAGE @@ -7,8 +8,7 @@ #endif #include /* tcgetattr(3), tcsetattr(3), struct termios, ECHO */ #include /* dup(2), execvp(3), fork(2), getopt(3), isatty(3), - * pipe(2), write(2), STDERR_FILENO, STDIN_FILENO, - * STDOUT_FILENO */ + * pipe(2), STDIN_FILENO */ static char *program_name = "peek"; @@ -17,7 +17,11 @@ int main(int argc, char *argv[]){ int eof; size_t i; char include_eof; - int outputs[] = {0 /* stdout */, 0 /* stderr */, 0 /* -p */}; + FILE *outputs[] = { + NULL /* stdout */, + NULL /* stderr */, + NULL /* -p */ + }; int p[2] = {0, 0}; struct termios t; @@ -28,15 +32,15 @@ int main(int argc, char *argv[]){ include_eof = 0; while((c = getopt(argc, argv, "1enopt")) != -1) switch(c){ - case '1': eof = '\n'; break; - case 'n': include_eof = 1; break; - case 'o': outputs[0] = STDOUT_FILENO; break; - case 'e': outputs[1] = STDERR_FILENO; break; + case '1': eof = '\n'; break; + case 'n': include_eof = 1; break; + case 'o': outputs[0] = stdout; break; + case 'e': outputs[1] = stderr; break; case 'p': if(pipe(p) != 0) goto die; - else - outputs[2] = p[1]; + else if((outputs[2] = fdopen(p[1], "ab")) == NULL) + goto die; break; case 't': if(isatty(STDIN_FILENO) != 1){ @@ -78,14 +82,12 @@ usage: fprintf(stderr, "Usage: %s (-1enot)" t.c_lflag ^= ECHO; tcsetattr(STDIN_FILENO, TCSAFLUSH, &t); - /* TODO redesign with fdopen(3) to use stdio for output */ do{ if((c = getc(stdin)) != eof || include_eof) for(i = 0; i < (sizeof outputs)/(sizeof *outputs); ++i) - if(outputs[i] != 0 - && write(outputs[i], &c, 1) - == -1){ + if(outputs[i] != NULL + && putc(c, outputs[i]) == EOF){ if(i == 2) - close(outputs[i]); + fclose(outputs[i]); outputs[i] = 0; } }while(c != eof);