shithub: kandr

ref: 91fc7321c2b7df934036f7b88ffdd5d6c826e941
dir: /ex/ex1-18.c/

View raw version
#include <u.h>
#include <libc.h>
#include <bio.h>

const MIN = 80;

/* 
Skip blank lines and trim trailing whitespace. 
*/
void
main(int, char*[])
{
	Biobuf	*in, *out;
	in = Bfdopen(0, OREAD);
	out = Bfdopen(1, OWRITE);

	u32int len = 0;
	while(1){
		char *line;
		int len, n, i, last;

		// Read
		line = Brdline(in, '\n');
		len = Blinelen(in);
		if(line == 0)
			break;
		if(len < 0)
			sysfatal("err: could not read line → %r\n");

		if(len < 2)
			continue;

		last = 0;
		for(i = 0; i < len-1; i++){
			switch(line[i]){
			case ' ':
			case '\t':
				break;
			default:
				last = i;
			}
		}

		if(last != len-1){
			len = last+2;
			line[last+1] = '\n';
		}

		// Write
		n = Bwrite(out, line, len);
		if(n < 0)
			sysfatal("err: could not write line → %r\n");
	}

	Bterm(in);
	Bterm(out);

	exits(nil);
}