1
0

now with stdio

This commit is contained in:
dtb 2024-01-01 22:13:30 -07:00
parent c2496ab0e8
commit 7392e319a9

View File

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