add option parsing

This commit is contained in:
Bruno BELANYI 2020-11-10 17:25:43 +01:00
parent 232dbbeb35
commit ba11946be5
4 changed files with 68 additions and 3 deletions

View file

@ -11,10 +11,12 @@ project(
sources = [
'src/image.c',
'src/main.c',
'src/options.c',
'src/ppm.c',
]
executable(
'buddhabrot',
sources : sources,
c_args : '-D_XOPEN_SOURCE',
)

View file

@ -3,6 +3,7 @@
#include <stdlib.h>
#include "image.h"
#include "options.h"
#include "ppm.h"
static void fill_image(struct image *image) {
@ -16,13 +17,17 @@ static void fill_image(struct image *image) {
}
}
int main(void) {
struct image *image = create_image(960, 540);
int main(int argc, char *argv[]) {
struct options opt = parse_options(&argc, &argv);
struct image *image = create_image(opt.w, opt.h);
if (!image)
err(EXIT_FAILURE, "could not allocate image");
fill_image(image);
print_ppm(image, stdout);
print_ppm(image, opt.output);
fclose(opt.output);
destroy_image(image);
return EXIT_SUCCESS;

43
src/options.c Normal file
View file

@ -0,0 +1,43 @@
#include "options.h"
#include <err.h>
#include <stdlib.h>
#include <unistd.h>
struct options parse_options(int *argc, char **argv[]) {
struct options opts = {
.output = stdout,
.w = 960,
.h = 540,
};
opterr = 0; // Deactivate error message from `getopt`
int opt;
while ((opt = getopt(*argc, *argv, "h:o:w:")) != -1) {
switch (opt) {
case 'h':
if (!sscanf(optarg, "%zu", &opts.h))
errx(EXIT_FAILURE, "could not parse height");
break;
case 'o':
if (!freopen(optarg, "w", opts.output))
err(EXIT_FAILURE, "could not open output file");
break;
case 'w':
if (!sscanf(optarg, "%zu", &opts.w))
errx(EXIT_FAILURE, "could not parse width");
break;
default:
fprintf(stderr, "Usage: %s [-o FILE] [-h HEIGHT] [-w WIDTH]\n",
(*argv)[0]);
exit(EXIT_FAILURE);
}
}
*argc -= optind;
*argv += optind;
return opts;
}

15
src/options.h Normal file
View file

@ -0,0 +1,15 @@
#ifndef OPTIONS_H
#define OPTIONS_H
#include <stddef.h>
#include <stdio.h>
struct options {
FILE *output;
size_t w;
size_t h;
};
struct options parse_options(int *argc, char **argv[]);
#endif /* !OPTIONS_H */