checkhex.c 2.14 KB
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void usage(void);
static int getLeftRight(FILE *, int *, int *);

#define	LINE_SIZE	80

int
main(int argc, char **argv)
{
    int		c, r;
    char	*genFileName, *goldFileName;
    FILE	*genFile, *goldFile;
    char	genLine[LINE_SIZE];
    int		genLeft, genRight;
    int		betweenFlag = 1;
    int		goldLeft = 0, goldRight = 0;
    int		goldLeftPrev, goldRightPrev;
    int		lineNumber = -1;

    while ((c = getopt(argc, argv, "")) != EOF) {
	switch(c) {
	case '?':
	    usage();
	}
    }
    if (argc - optind != 2)
	usage();

    genFileName = argv[optind];
    if ((genFile = fopen(genFileName, "r")) == NULL) {
 	fprintf(stderr, "checkhex: %s: %s\n", genFileName, strerror(errno));
	exit(1);
    }
    goldFileName = argv[optind+1];
    if ((goldFile = fopen(goldFileName, "r")) == NULL) {
	fprintf(stderr, "checkhex: %s: %s\n", goldFileName, strerror(errno));
	exit(1);
    }
    while (getLeftRight(genFile, &genLeft, &genRight) != EOF) {
	lineNumber += 2;
	if (!betweenFlag) {
	    if (getLeftRight(goldFile, &goldLeft, &goldRight) == EOF) {
		betweenFlag = 1;
		rewind(goldFile);
	    }
	}
	if (betweenFlag) {
	    if ((genLeft == goldLeft) && (genRight == goldRight)) {
		continue;
	    } else {
		goldLeftPrev = goldLeft;
		goldRightPrev = goldRight;
		while ((r = getLeftRight(goldFile, &goldLeft, &goldRight))
				!= EOF) {
		    if ((goldLeftPrev != goldLeft) ||
			(goldRightPrev != goldRight))
			break;
		}
		betweenFlag = 0;
	    }
	}
	if ((genLeft != goldLeft) || (genRight != goldRight)) {
	    fprintf(stderr,
	     "checkhex: mismatch on line %d of %s (%04x,%04x) vs (%04x,%04x)\n",
	     lineNumber, genFileName, genLeft, genRight, goldLeft, goldRight);
	    exit(1);
	}
    }
    return(0);
}

static void
usage(void)
{
    fprintf(stderr, "checkhex <generated .hex file> <golden .hex file>\n");
    exit(1);
}

static int
getLeftRight(FILE *f, int *leftp, int *rightp)
{
    int r;

    if ((r = fscanf(f, "%x\n%x", leftp, rightp)) == EOF)
	return(EOF);
    else if (r != 2) {
	fprintf(stderr, "checkhex: syntax error\n");
	exit(1);
    } else {
	return(0);
    }
}