/* bigfile.c
 *
 * $Id: bigfile.c,v 1.3 2000/12/04 03:37:03 alderman Exp $
 *
 * Big file: read a big file sequentially.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> 

#include "global.h"

int readMeg(char *buf, int fd);

int main(int argc, char *argv[]) {
        int fd, i;
        char buf[NUMBYTES+1];

	if(argc != 2) {
		fprintf(stderr, 
			"Specify filename to read on command line.\n");
		exit(1);
	}


        memset(buf, '\0', NUMBYTES);

        fd = open(argv[1], O_RDONLY, NULL);

        if(fd < 1) {
                printf("error: fd %d\n",fd);
        }
        for (i = 0; i < HOWBIG; i++) {
                if(readMeg(buf, fd) < 0) {
                        fprintf(stderr, "Exiting with i = %d.\n", i);
                        exit(1);
                }
        }
	exit(0);
}
               

int readMeg(char *buf, int fd) {
        int curByte = 0;
        int rv;
        while(1) {
                rv = read(fd, buf, NUMBYTES - curByte);
                curByte += rv;
                if(rv > 0) {
                        // fprintf(stderr, "Read %d bytes.\n",rv);
                        if (curByte < NUMBYTES) {
                                continue;
                        } else {
				return curByte;
			}
                } else if (rv == 0) {
                        fprintf(stderr, "Read Zero bytes.\n");
                        return rv;
                } else {
                        fprintf(stderr, "Read returned negative: %d.\n", rv);
                        return rv;
                }
        }
        return rv;
}
