csv-to-bin.c

#include <sys/stat.h>

#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "lootsack.h"

__dead void usage(const char *progname);

__dead void
usage(const char *progname)
{
	fprintf(stderr, "Usage:\n\t%s [-v] [-i infile] -o outfile\n", progname);
	exit(1);
}

int verbose;

int
main(int argc, char **argv)
{
	struct treasure_file_header h;
	struct treasure *items;
	char ch;
	int in_fd, out_fd;

	if (argc < 2)
		usage(*argv); /* does not return */

	in_fd = STDIN_FILENO;
	out_fd = STDOUT_FILENO;
	while ((ch = getopt(argc, argv, "vi:o:")) != -1) {
		switch (ch) {
		case 'i':
			if (unveil(optarg, "r") == -1)
				err(1, "read unveil");
			if ((in_fd = open(optarg, O_RDONLY)) == -1)
				err(1, "%s", optarg);
			break;
		case 'o':
			if (unveil(optarg, "wc") == -1)
				err(1, "write unveil");
			if ((out_fd = open(optarg,  O_WRONLY | O_CREAT,
			    S_IRUSR | S_IWUSR | S_IRGRP)) == -1)
				err(1, "%s", optarg);
			break;
		case 'v':
			verbose = 1;
			break;
		default:
			usage(*argv); /* does not return */
		}
	}

	if (pledge("stdio unveil rpath", NULL) == -1)
		err(1, "pledge");

	if (pledge(NULL, NULL) == -1)
		err(1, "finalize pledge");

	if (unveil(NULL, NULL) == -1)
		err(1, "finalize unveil");

	if (read_treasure_csv(in_fd, &h, &items) == -1)
		err(1, "read_treasure_csv");

	if (write_treasure_bin(out_fd, items, h.num_entries) == -1)
		err(1, "write_treasure_bin");

	return 0;
}