getopt
This commit is contained in:
parent
b5b554bf31
commit
561a344f30
3 changed files with 68 additions and 0 deletions
15
getopt/Makefile
Normal file
15
getopt/Makefile
Normal file
|
|
@ -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
|
||||||
15
getopt/getopt.c
Normal file
15
getopt/getopt.c
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
38
getopt/getopt_long.c
Normal file
38
getopt/getopt_long.c
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
#include <getopt.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#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;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue