9p / who / tweedy / 9C / 1


File Copying

Two ways of re-creating K&R’s File Copying program are presented here. The first (using bio.h) is more instructive; the second (using read() and write()) is more concise.

Code (bio.h version)

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

#define STDIN   0
#define STDOUT  1

/*      copy input to output; 1st version (using bio.h)  */

void
main()
{
        Biobuf *bstdin, *bstdout;               /* create buffers for stdin and stdout contents */
        char c;

        bstdin = Bfdopen(STDIN, OREAD);         /* connect std in to our buffer */
        bstdout = Bfdopen(STDOUT, OWRITE);      /* connect std out */

        c = Bgetc(bstdin);
        while(c >= 0){              /* Bgetc() returns -1 at EOF */
                Bputc(bstdout, c);
                Bflush(bstdout);                /* push the buffer to std out */
                c = Bgetc(bstdin);
        }

exits(0);
}

Output

$ 9c bio.c
$ 9l bio.o -o bio
$ ./bio
test
test
123
123

Code (read() and write() version)

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

#define STDIN   0
#define STDOUT  1

/*      copy input to output; 1st version (using read() and write())     */

void
main()
{
        char c;

        read(STDIN, &c, 1);
        while(c != 'q'){
                write(STDOUT, &c, 1);
                read(STDIN, &c, 1);
        }

exits(0);
}

Output (read() and write() version)

$ 9c copy.c
$ 9l copy.o -o copy
$ ./copy
testing
testing
321
321
q



tweedy