From 561a344f3091c7f99c0fd3091db442c6d58ecbda Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Fri, 14 Nov 2025 20:59:40 +0100 Subject: [PATCH] getopt --- getopt/Makefile | 15 +++++++++++++++ getopt/getopt.c | 15 +++++++++++++++ getopt/getopt_long.c | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 getopt/Makefile create mode 100644 getopt/getopt.c create mode 100644 getopt/getopt_long.c diff --git a/getopt/Makefile b/getopt/Makefile new file mode 100644 index 0000000..10168b0 --- /dev/null +++ b/getopt/Makefile @@ -0,0 +1,15 @@ +CC = gcc +CFLAGS = -Wall -O2 + +all: getopt.elf getopt_long.elf + +getopt.elf: getopt.c + @echo CC $@ + @$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +getopt_long.elf: getopt_long.c + @echo CC $@ + @$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +clean: + rm -f *.elf diff --git a/getopt/getopt.c b/getopt/getopt.c new file mode 100644 index 0000000..2e5c8b4 --- /dev/null +++ b/getopt/getopt.c @@ -0,0 +1,15 @@ +#include +#include + +int main(int argc, char *argv[]) { + int opt; + while ((opt = getopt(argc, argv, "hf:o:")) != -1) { + switch (opt) { + case 'h': puts("Help"); break; + case 'f': printf("File: %s\n", optarg); break; + case 'o': printf("Output: %s\n", optarg); break; + default: fprintf(stderr, "Usage: %s [-h] [-f file] [-o output]\n", argv[0]); return 1; + } + } + return 0; +} diff --git a/getopt/getopt_long.c b/getopt/getopt_long.c new file mode 100644 index 0000000..a888e6e --- /dev/null +++ b/getopt/getopt_long.c @@ -0,0 +1,38 @@ +#include +#include +#include + +#define VERSION "0.0.1" + +int main(int argc, char *argv[]) { + int opt; + int option_index = 0; + static struct option long_opts[] = { + {"help", no_argument, 0, 'h'}, + {"file", required_argument, 0, 'f'}, + {"output", required_argument, 0, 'o'}, + {"version", no_argument, 0, 'v'}, + {0, 0, 0, 0}, + }; + + int has_file = 0; + char a[128]; + + while ((opt = getopt_long(argc, argv, "hvf:o:", long_opts, &option_index)) != -1) { + switch (opt) { + case 'h': puts("Help"); break; + case 'f': + printf("File: %s\n", optarg); + strncpy(a, optarg, 127); + has_file = 1; + break; + case 'o': printf("Output: %s\n", optarg); break; + case 'v': printf("Version: v%s\n", VERSION); break; + default: return 1; + } + } + + if (has_file) + printf("Using file: %s\n", a); + return 0; +}