scopy.c

/*
 * Write integers out as integers, creating a binary file
 * Usage: scopy [ number of numbers ]
 * default is 10 numbers
 * 
 * Matt Bishop, ECS 36A, Fall 2019
 *
 * April 22, 2025
 *	-- original version
 */
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/types.h>

/*
 * macros
 */
#define MAXBUF	1024
#define DEFNUM	10
#define FILENAME "binint"

/*
 * the main routine
 */
int main(int argc, char *argv[])
{
	FILE *outfp;		/* output file pointers */
	long ibuf[MAXBUF];	/* buffer */
	long nwrite;		/* number of bytes to write */
	int i;

	/*
	 * get the argument;if too big,
	 * say so and reduce to MAXBUF
	 */
	if (argc == 1)
		nwrite = DEFNUM;
	else if (argc == 2){
		nwrite = strtol(argv[1], NULL, 10);
		if (nwrite == LONG_MAX || nwrite == LONG_MIN){
			perror(argv[1]);
			exit(1);
		}
		if (nwrite > MAXBUF)
			nwrite = MAXBUF;
	}
	else{
		fprintf(stderr, "Usage: %s [ number of numbers ]\n", argv[0]);
		exit(1);
	}

	/*
	 * now generate nwrite numbers
	 */
	for(i = 0; i < nwrite; i++){
		ibuf[i] = rand();
		printf("%2d.\t%ld\t%#lx\t%0lo\n", i, ibuf[i], ibuf[i], ibuf[i]);
	}

	/*
	 * write them out as binary numbers
	 */
	if ((outfp = fopen(FILENAME, "w")) == NULL){
		fprintf(stderr, "%s: could not open\n", argv[2]);
		return(1);
	}
	if (fwrite(ibuf, sizeof(long int), nwrite, outfp) != nwrite){
		fprintf(stderr, "%s: write error; quitting\n", argv[2]);
		return(1);
	}
	(void) fclose(outfp);

	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh