Commit 2bef6c4d by David Llewellyn-Jones

Add datadir command line option

parent 658a68ea
......@@ -16,6 +16,7 @@
#include <string.h>
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include <argp.h>
///////////////////////////////////////////////////////////////////
// Defines
......@@ -28,6 +29,18 @@
///////////////////////////////////////////////////////////////////
// Global variables
const char *argp_program_version = "useless 0.01";
const char *argp_program_bug_address = "<david@flypig.co.uk>";
static char doc[] = "A pretty useless poem transformation program.";
static struct argp_option options[] = {
{"datadir", 'd', "path", 0, "Data directory to use (defaults to '" USELESSDIR "')"},
{0}
};
typedef struct {
char * datadir;
} arguments;
static const int colour[12][2] = {
{0, 31}, // Red
{1, 31}, // Light red
......@@ -46,11 +59,42 @@ static const int colour[12][2] = {
///////////////////////////////////////////////////////////////////
// Function prototypes
char * generate_data_path (char const * leaf, arguments const * args);
///////////////////////////////////////////////////////////////////
// Function definitions
static error_t parse_opt(int key, char *arg, struct argp_state *state) {
arguments * args = state->input;
switch (key) {
case 'd':
args->datadir = realloc(args->datadir, strlen(arg) + 1);
strcpy(args->datadir, arg);
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = {options, parse_opt, NULL, doc, 0, 0, 0 };
char * generate_data_path (char const * leaf, arguments const * args) {
char * result = NULL;
int length;
if (leaf) {
length = snprintf(NULL, 0, "%s/%s", args->datadir, leaf);
result = malloc(length + 2);
snprintf(result, length + 2, "%s/%s", args->datadir, leaf);
}
return result;
}
int main (int argc, char **argv) {
char * filename = USELESSDIR "/dong.txt";
char * filename;
arguments args;
PCRE2_UCHAR8 * regexp = (PCRE2_UCHAR8 *)"[Dd]ong";
PCRE2_UCHAR8 * subs = (PCRE2_UCHAR8 *)"Pobble";
PCRE2_UCHAR8 line[MAX_LINE_LEN];
......@@ -63,6 +107,14 @@ int main (int argc, char **argv) {
PCRE2_SIZE offset;
int stanza;
// Parse the command line arguments
args.datadir = malloc(strlen(USELESSDIR) + 1);
strcpy(args.datadir, USELESSDIR);
argp_parse(& argp, argc, argv, 0, 0, & args);
printf("datadir: %s\n", args.datadir);
// Open the file using the datadir prefix
filename = generate_data_path ("dong.txt", & args);
printf("Opening poem file: %s\n\n", filename);
// Open the file containing poetry
......@@ -101,6 +153,9 @@ int main (int argc, char **argv) {
printf ("\e[0m");
free(filename);
free(args.datadir);
// All paths lead here
return 0;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment