pipetools/csv2bin.c

81 lines
1.4 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <getopt.h>
#include <err.h>
#define CHUNK_DEFAULT (0x1000)
int
usage(const char* progname)
{
fprintf(stderr, "usage: %s [-c chunk] <-s size | -u size | -f size | -d size>\n", progname);
return 1;
}
int
main(int argc, char** argv)
{
int optch;
int cflag = 0;
const char* carg = NULL;
enum { INV = -1, INT, UINT, FLOAT, DOUBLE } tflag = INV;
const char* sizearg = NULL;
while ((optch = getopt(argc, argv, "c:s:u:f:d:h")) != -1) {
switch (optch) {
case 'c':
cflag = 1;
carg = optarg;
break;
case 's':
tflag = INT;
sizearg = optarg;
break;
case 'u':
tflag = UINT;
sizearg = optarg;
break;
case 'f':
tflag = FLOAT;
sizearg = optarg;
break;
case 'd':
tflag = FLOAT;
sizearg = optarg;
break;
case 'h':
default:
return usage(*argv);
}
}
if (tflag == INV)
return usage(*argv);
const char* fmt = (char*[]){ "%d,", "%u,", "%f,", "%lf," }[tflag];
size_t membsize = strtoull(sizearg, NULL, 10);
size_t chunk = cflag? strtoull(carg, NULL, 10) : CHUNK_DEFAULT;
uint8_t* buffer = aligned_alloc(0x40, chunk * membsize);
if (buffer == NULL)
err(1, "malloc()");
while (!feof(stdin)) {
size_t i;
for (i = 0; i < chunk; ++i) {
if (scanf(fmt, &buffer[i * membsize]) != 1)
break;
}
fwrite(buffer, membsize, i, stdout);
}
return 0;
}