9p / who / tweedy / 9C / 1


Exercise 1.10: Escape Tabs, Backspaces, and Backslashes

Code

#include <u.h>
#include <libc.h>
#include <bio.h>

#define STDIN   0
#define STDOUT  1

/* escape Tabs, backspaces, and backslashes  */

void
main()
{
    Biobuf *bstdin, *bstdout;
    bstdin = Bfdopen(STDIN, OREAD);
    bstdout = Bfdopen(STDOUT, OWRITE);
    char c;

    c = Bgetc(bstdin);
    while(c >= 0){
        if(c == '\t'){
            Bputc(bstdout, '\\');
            Bputc(bstdout, 't');
        }
        if(c == '\b'){
            Bputc(bstdout, '\\');
            Bputc(bstdout, 'b');
        }
        if(c == '\\'){
            Bputc(bstdout, '\\');
            Bputc(bstdout, '\\');
        }
        else
            Bputc(bstdout, c);
        Bflush(bstdout);
        c = Bgetc(bstdin);
    }

exits(0);
}

Output

$ 9c esc.c; 9l esc.o -o esc
$ ./esc 
Tabs    and \backslashes
Tabs\t  and \\backslashes



tweedy