Eliminating the getopt disgrace.
This commit is contained in:
		
							
								
								
									
										41
									
								
								tee.c
									
									
									
									
									
								
							
							
						
						
									
										41
									
								
								tee.c
									
									
									
									
									
								
							@@ -5,38 +5,49 @@
 | 
			
		||||
#include <unistd.h>
 | 
			
		||||
#include "util.h"
 | 
			
		||||
 | 
			
		||||
static void
 | 
			
		||||
usage(void)
 | 
			
		||||
{
 | 
			
		||||
	eprintf("usage: %s [-a] [file...]\n", argv0);
 | 
			
		||||
	exit(1);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
int
 | 
			
		||||
main(int argc, char *argv[])
 | 
			
		||||
{
 | 
			
		||||
	bool aflag = false;
 | 
			
		||||
	char buf[BUFSIZ], c;
 | 
			
		||||
	char buf[BUFSIZ];
 | 
			
		||||
	int i, nfps = 1;
 | 
			
		||||
	size_t n;
 | 
			
		||||
	FILE **fps;
 | 
			
		||||
 | 
			
		||||
	while((c = getopt(argc, argv, "a")) != -1)
 | 
			
		||||
		switch(c) {
 | 
			
		||||
		case 'a':
 | 
			
		||||
			aflag = true;
 | 
			
		||||
			break;
 | 
			
		||||
		default:
 | 
			
		||||
			exit(EXIT_FAILURE);
 | 
			
		||||
		}
 | 
			
		||||
	ARGBEGIN {
 | 
			
		||||
	case 'a':
 | 
			
		||||
		aflag = true;
 | 
			
		||||
		break;
 | 
			
		||||
	default:
 | 
			
		||||
		usage();
 | 
			
		||||
	} ARGEND;
 | 
			
		||||
 | 
			
		||||
	if(!(fps = malloc(sizeof *fps)))
 | 
			
		||||
		eprintf("malloc:");
 | 
			
		||||
	fps[nfps-1] = stdout;
 | 
			
		||||
 | 
			
		||||
	for(; optind < argc; optind++) {
 | 
			
		||||
	for(; argc > 0; argc--, argv++) {
 | 
			
		||||
		if(!(fps = realloc(fps, ++nfps * sizeof *fps)))
 | 
			
		||||
			eprintf("realloc:");
 | 
			
		||||
		if(!(fps[nfps-1] = fopen(argv[optind], aflag ? "a" : "w")))
 | 
			
		||||
			eprintf("fopen %s:", argv[optind]);
 | 
			
		||||
		if(!(fps[nfps-1] = fopen(argv[0], aflag ? "a" : "w")))
 | 
			
		||||
			eprintf("fopen %s:", argv[0]);
 | 
			
		||||
	}
 | 
			
		||||
	while((n = fread(buf, 1, sizeof buf, stdin)) > 0)
 | 
			
		||||
		for(i = 0; i < nfps; i++)
 | 
			
		||||
	while((n = fread(buf, 1, sizeof buf, stdin)) > 0) {
 | 
			
		||||
		for(i = 0; i < nfps; i++) {
 | 
			
		||||
			if(fwrite(buf, 1, n, fps[i]) != n)
 | 
			
		||||
				eprintf("%s: write error:", buf);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	if(ferror(stdin))
 | 
			
		||||
		eprintf("<stdin>: read error:");
 | 
			
		||||
	return EXIT_SUCCESS;
 | 
			
		||||
 | 
			
		||||
	return 0;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user