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 <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 <string.h> /* strerror(3) */
#if !defined EX_OK || !defined EX_OSERR || !defined EX_USAGE
@ -7,8 +8,7 @@
#endif
#include <termios.h> /* tcgetattr(3), tcsetattr(3), struct termios, ECHO */
#include <unistd.h> /* 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);