bin-to-csv.c

#include <sys/stat.h>

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

#include "lootsack.h"

int verbose = 0;

__dead void usage(const char *progname);

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


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;

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

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

	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 (unveil(NULL, NULL) == -1)
		err(1, "finalize unveil");

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

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

	return 0;
}