mirror of
https://github.com/eddyem/snippets_library.git
synced 2026-11-23 22:30:30 +03:00
Compare commits
6 Commits
52970bfc04
...
v0.3.5-r1
| Author | SHA1 | Date | |
|---|---|---|---|
| 503325b68f | |||
| 566ca36af8 | |||
| f1162e4df1 | |||
| 850002d800 | |||
| 2525224423 | |||
| ca4565faec |
@@ -1,2 +0,0 @@
|
||||
# snippets_library
|
||||
The common library for my most usefull snippets
|
||||
80
Readme.md
80
Readme.md
@@ -1,4 +1,4 @@
|
||||
# `libusefull_macros` A collection of useful C snippets for Linux
|
||||
# `libusefull_macros` - A collection of useful C snippets for Linux
|
||||
|
||||
**Version:** 0.3.5
|
||||
**Author:** Edward V. Emelianov (<edward.emelianoff@gmail.com>)
|
||||
@@ -47,14 +47,14 @@ Linux application development. It covers:
|
||||
|
||||
- Colored, locale-aware terminal output
|
||||
- Safe memory allocation and memory-mapped file I/O
|
||||
- GNU `getopt_long`-style command-line argument parsing with typesafe callbacks
|
||||
- INIlike configuration file reading/writing
|
||||
- Daemonization with PIDfile management
|
||||
- Threadsafe ring buffer for producerconsumer patterns
|
||||
- GNU `getopt_long`-style command-line argument parsing with type-safe callbacks
|
||||
- INI-like configuration file reading/writing
|
||||
- Daemonization with PID-file management
|
||||
- Thread-safe ring buffer for producer-consumer patterns
|
||||
- FIFO/LIFO linked list
|
||||
- TCP and UNIX socket server/client framework with builtin HTTP parsing and keyvalue handler dispatch
|
||||
- Serial port (TTY) management with nonstandard baud rates
|
||||
- Filebased logging with multiple severity levels
|
||||
- TCP and UNIX socket server/client framework with built-in HTTP parsing and key-value handler dispatch
|
||||
- Serial port (TTY) management with non-standard baud rates
|
||||
- File-based logging with multiple severity levels
|
||||
- `gettext` integration for internationalization
|
||||
|
||||
All public identifiers are prefixed with `sl_` (for "snippets library") to avoid naming collisions.
|
||||
@@ -214,7 +214,7 @@ MALLOC(type, size) // allocate without declaration
|
||||
FREE(ptr) // free and set to NULL
|
||||
```
|
||||
|
||||
**Memorymapped files:**
|
||||
**Memory-mapped files:**
|
||||
|
||||
```c
|
||||
typedef struct { char *data; size_t len; } sl_mmapbuf_t;
|
||||
@@ -222,7 +222,7 @@ sl_mmapbuf_t *sl_mmap(char *filename);
|
||||
void sl_munmap(sl_mmapbuf_t *b);
|
||||
```
|
||||
|
||||
Maps a file readonly into memory; `sl_munmap` unmaps and frees the structure.
|
||||
Maps a file read-only into memory; `sl_munmap` unmaps and frees the structure.
|
||||
|
||||
**System memory query:**
|
||||
|
||||
@@ -267,12 +267,12 @@ pointer may be `NULL` to only check validity.
|
||||
|
||||
### Console / Terminal I/O
|
||||
|
||||
For noncanonical, noecho terminal input:
|
||||
For non-canonical, no-echo terminal input:
|
||||
|
||||
```c
|
||||
void sl_setup_con(void); // switch terminal to raw mode
|
||||
void sl_restore_con(void); // restore original terminal settings
|
||||
int sl_read_con(void); // nonblocking read (0 if no key)
|
||||
int sl_read_con(void); // non-blocking read (0 if no key)
|
||||
int sl_getchar(void); // blocking read of one character
|
||||
```
|
||||
|
||||
@@ -284,7 +284,7 @@ int ch = sl_getchar();
|
||||
sl_restore_con();
|
||||
```
|
||||
|
||||
**Important:** These functions are **not threadsafe** they use a global `struct termios2`.
|
||||
**Important:** These functions are **not thread-safe** - they use a global `struct termios2`.
|
||||
|
||||
---
|
||||
|
||||
@@ -333,7 +333,7 @@ Built on top of `getopt_long`. Supports:
|
||||
|
||||
- Short and long options
|
||||
- Required, optional, and no arguments
|
||||
- Multiple occurrences of the same option (multiparameters)
|
||||
- Multiple occurrences of the same option (multi-parameters)
|
||||
- Six data types: `int`, `long long`, `double`, `float`, `char*`, and function callback
|
||||
- Automatic help generation
|
||||
|
||||
@@ -343,7 +343,7 @@ Built on top of `getopt_long`. Supports:
|
||||
typedef struct {
|
||||
const char *name; // long option (NULL for short-only)
|
||||
sl_hasarg_e has_arg; // NO_ARGS, NEED_ARG, OPT_ARG, or MULT_PAR
|
||||
int *flag; // NULL return val; else set *flag = val
|
||||
int *flag; // NULL - return val; else set *flag = val
|
||||
int val; // short option character or flag value
|
||||
sl_argtype_e type; // arg_int, arg_longlong, arg_double, arg_float,
|
||||
// arg_string, arg_function
|
||||
@@ -368,7 +368,7 @@ void sl_showhelp(int oindex, sl_option_t *options);
|
||||
void sl_helpstring(char *s); // customize help header
|
||||
```
|
||||
|
||||
After calling `sl_parseargs`, `argc` and `argv` are updated to point to remaining nonoption
|
||||
After calling `sl_parseargs`, `argc` and `argv` are updated to point to remaining non-option
|
||||
arguments.
|
||||
|
||||
**Example:**
|
||||
@@ -385,14 +385,14 @@ sl_option_t opts[] = {
|
||||
int main(int argc, char **argv) {
|
||||
sl_init();
|
||||
sl_parseargs(&argc, &argv, opts);
|
||||
// argc, argv now contain nonoption arguments
|
||||
// argc, argv now contain non-option arguments
|
||||
}
|
||||
```
|
||||
|
||||
**Multiparameters** (`MULT_PAR`): Options that may appear multiple times. The library allocates a
|
||||
`NULL`terminated array of pointers, each pointing to a newly allocated value. For `arg_string`,
|
||||
**Multi-parameters** (`MULT_PAR`): Options that may appear multiple times. The library allocates a
|
||||
`NULL`-terminated array of pointers, each pointing to a newly allocated value. For `arg_string`,
|
||||
each element is a pointer to a `strdup`'d string; for numeric types, each is a pointer to a
|
||||
heapallocated number.
|
||||
heap-allocated number.
|
||||
|
||||
**Function callback** (`arg_function`): The callback must have signature `int (*fn)(void *arg)` and
|
||||
receives a `strdup`'d argument string.
|
||||
@@ -404,7 +404,7 @@ than the default `sl_showhelp` (which calls `exit(-1)`).
|
||||
|
||||
### Configuration Files
|
||||
|
||||
Reads keyvalue pairs from a file and treats them as commandline options.
|
||||
Reads key-value pairs from a file and treats them as command-line options.
|
||||
|
||||
```c
|
||||
int sl_conf_readopts(const char *filename, sl_option_t *options);
|
||||
@@ -421,7 +421,7 @@ key2
|
||||
key3 = "quoted value"
|
||||
```
|
||||
|
||||
Each noncomment line is converted to `--key=value` (or `--key` if no value) and passed to
|
||||
Each non-comment line is converted to `--key=value` (or `--key` if no value) and passed to
|
||||
`sl_parseargs`. Returns the number of recognized options.
|
||||
|
||||
`sl_print_opts` generates a string representation of current option values (useful for debugging or
|
||||
@@ -435,7 +435,7 @@ saving state). The returned string must be freed with `free()`.
|
||||
int sl_daemonize(void);
|
||||
void sl_check4running(char *selfname, char *pidfilename);
|
||||
char *sl_getPSname(pid_t pid);
|
||||
void sl_iffound_deflt(pid_t pid); // WEAK overridable
|
||||
void sl_iffound_deflt(pid_t pid); // WEAK - overridable
|
||||
```
|
||||
|
||||
`sl_daemonize()`:
|
||||
@@ -463,7 +463,7 @@ void sl_iffound_deflt(pid_t pid) {
|
||||
|
||||
### FIFO / LIFO Linked List
|
||||
|
||||
A simple singlylinked list with both head and tail pointers.
|
||||
A simple singly-linked list with both head and tail pointers.
|
||||
|
||||
```c
|
||||
typedef struct sl_buff_node {
|
||||
@@ -483,7 +483,7 @@ the data if needed.
|
||||
|
||||
### Ring Buffer
|
||||
|
||||
A threadsafe, fixedsize ring buffer for byte streams, protected by `pthread_mutex_t`.
|
||||
A thread-safe, fixed-size ring buffer for byte streams, protected by `pthread_mutex_t`.
|
||||
|
||||
```c
|
||||
typedef struct {
|
||||
@@ -517,7 +517,7 @@ Key behaviors:
|
||||
|
||||
### TCP / UNIX Socket Server & Client
|
||||
|
||||
A highlevel socket framework supporting TCP and UNIX domain sockets, with builtin HTTP method
|
||||
A high-level socket framework supporting TCP and UNIX domain sockets, with built-in HTTP method
|
||||
detection.
|
||||
|
||||
**Socket types:**
|
||||
@@ -537,7 +537,7 @@ void sl_sock_delete(sl_sock_t **sock);
|
||||
|
||||
- `path` for UNIX sockets: file path; prefix with `\0` or `@` for abstract namespace.
|
||||
- `path` for INET sockets: `"host:port"` (client) or `":port"` (server).
|
||||
- `handlers`: `NULL`terminated array of keyvalue handlers (see below).
|
||||
- `handlers`: `NULL`-terminated array of key-value handlers (see below).
|
||||
- `bufsiz`: internal ring buffer size (minimum 256).
|
||||
|
||||
**Sending data:**
|
||||
@@ -578,7 +578,7 @@ typedef enum {
|
||||
} sl_sock_hresult_e;
|
||||
```
|
||||
|
||||
Builtin handlers for common types:
|
||||
Built-in handlers for common types:
|
||||
|
||||
```c
|
||||
sl_sock_hresult_e sl_sock_inthandler(...); // int64_t
|
||||
@@ -607,7 +607,7 @@ void sl_sock_defmsghandler(sl_sock_t *sock, sl_sock_hresult_e (*h)(struct sl_soc
|
||||
|
||||
The server thread automatically handles `POLLIN` events, parses messages using `sl_get_keyval`, and
|
||||
dispatches them to matching handlers. HTTP `GET`/`POST` requests are partially parsed: `GET`
|
||||
parameters are URLdecoded and dispatched; `POST` data is accumulated and then parsed.
|
||||
parameters are URL-decoded and dispatched; `POST` data is accumulated and then parsed.
|
||||
|
||||
---
|
||||
|
||||
@@ -634,7 +634,7 @@ void sl_tty_close(sl_tty_t **descr);
|
||||
int sl_tty_tmout(double usec);
|
||||
```
|
||||
|
||||
Format string: three characters data bits (58), parity (N/E/O/0/1), stop bits (1/2). Example:
|
||||
Format string: three characters - data bits (5-8), parity (N/E/O/0/1), stop bits (1/2). Example:
|
||||
`"8N1"`.
|
||||
|
||||
Uses `struct termios2` via `ioctl(TCGETS2/TCSETS2)` to support arbitrary baud rates (not limited to
|
||||
@@ -667,7 +667,7 @@ int sl_get_suboption(char *str, sl_suboption_t *opt);
|
||||
```
|
||||
|
||||
The input string is tokenized on `:` and `,`; each token is matched against option names
|
||||
(caseinsensitive).
|
||||
(case-insensitive).
|
||||
|
||||
---
|
||||
|
||||
@@ -677,8 +677,8 @@ The input string is tokenized on `:` and `,`; each token is matched against opti
|
||||
const char *sl_libversion(void); // returns PACKAGE_VERSION string
|
||||
double sl_dtime(void); // UNIX time as double (seconds)
|
||||
long sl_random_seed(void); // seed from /dev/random or time
|
||||
int sl_canread(int fd); // nonblocking select() for read
|
||||
int sl_canwrite(int fd); // nonblocking select() for write
|
||||
int sl_canread(int fd); // non-blocking select() for read
|
||||
int sl_canwrite(int fd); // non-blocking select() for write
|
||||
```
|
||||
|
||||
---
|
||||
@@ -687,13 +687,13 @@ int sl_canwrite(int fd); // nonblocking select() for write
|
||||
|
||||
| Structure | Purpose |
|
||||
|-----------|---------|
|
||||
| `sl_option_t` | Commandline option descriptor |
|
||||
| `sl_suboption_t` | Suboption descriptor |
|
||||
| `sl_option_t` | Command-line option descriptor |
|
||||
| `sl_suboption_t` | Sub-option descriptor |
|
||||
| `sl_tty_t` | Serial port state |
|
||||
| `sl_log_t` | Log file descriptor |
|
||||
| `sl_mmapbuf_t` | Memorymapped file |
|
||||
| `sl_mmapbuf_t` | Memory-mapped file |
|
||||
| `sl_list_t` | Linked list node |
|
||||
| `sl_ringbuffer_t` | Threadsafe ring buffer |
|
||||
| `sl_ringbuffer_t` | Thread-safe ring buffer |
|
||||
| `sl_sock_t` | Socket state (client or server) |
|
||||
| `sl_sock_hitem_t` | Socket handler item |
|
||||
| `sl_sock_int_t` | Timestamped `int64_t` |
|
||||
@@ -710,8 +710,8 @@ The repository includes several example programs in the `examples/` directory:
|
||||
| Example | Demonstrates |
|
||||
|---------|-------------|
|
||||
| `helloworld` | Minimal usage: `sl_init`, colored output, `sl_setup_con`/`sl_getchar`/`sl_restore_con` |
|
||||
| `options` + `cmdlnopts` | Full commandline parsing with all types, logging, serial port, signals |
|
||||
| `conffile` | Configuration file reading, `sl_print_opts`, multiparameters |
|
||||
| `options` + `cmdlnopts` | Full command-line parsing with all types, logging, serial port, signals |
|
||||
| `conffile` | Configuration file reading, `sl_print_opts`, multi-parameters |
|
||||
| `fifo` | LIFO and FIFO list operations |
|
||||
| `ringbuffer` | Ring buffer creation, line reading, overflow handling |
|
||||
| `clientserver` | Socket server/client with custom handlers, bit flags, logging |
|
||||
@@ -744,7 +744,7 @@ expected in the `locale/` directory. The library generates `.po` and `.mo` files
|
||||
- **Ring buffer:** all operations are protected by a `pthread_mutex_t`.
|
||||
- **Logging:** file writes are guarded with `flock(LOCK_EX)`.
|
||||
- **Sockets:** server thread uses `poll()`; client read thread is separate; send operations lock the socket mutex.
|
||||
- **Console I/O:** `sl_setup_con`/`sl_read_con`/`sl_getchar`/`sl_restore_con` are **not** threadsafe (global terminal state).
|
||||
- **Console I/O:** `sl_setup_con`/`sl_read_con`/`sl_getchar`/`sl_restore_con` are **not** thread-safe (global terminal state).
|
||||
|
||||
---
|
||||
|
||||
|
||||
8
daemon.c
8
daemon.c
@@ -140,9 +140,11 @@ int sl_daemonize(){
|
||||
close(STDIN_FILENO);
|
||||
close(STDOUT_FILENO);
|
||||
close(STDERR_FILENO);
|
||||
if(open("/dev/null", O_RDWR) < 0) return -1;
|
||||
if(dup(0) < 0) return -1;
|
||||
if(dup(0) < 0) return -1;
|
||||
int ofd = open("/dev/null", O_RDWR);
|
||||
if(ofd < 0) return -1;
|
||||
if(dup(ofd) < 0) return -1; // STDIN
|
||||
if(dup(ofd) < 0) return -1; // STDOUT
|
||||
if(dup(ofd) < 0) return -1; // STDERR
|
||||
if(SIG_ERR == signal(SIGHUP, SIG_IGN)) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -52,9 +52,11 @@ static glob_pars const Gdefault = {
|
||||
* name has_arg flag val type argptr help
|
||||
* BE carefull! The `help` field is mandatory! Omitting it equivalent of 'end_option'
|
||||
*/
|
||||
// if val < 33 || val > 127 we mean this like long-only option;
|
||||
// you can repeat the same `val` for several long-only options without any problem
|
||||
static sl_option_t cmdlnopts[] = {
|
||||
// short option in only-long options should be zeroed, or you can add flag to set it to given value
|
||||
{"lo0", NEED_ARG, NULL, 0, arg_int, APTR(&G.lo0), _("only long arg 0 (int)")},
|
||||
{"longonly",NEED_ARG, NULL, 0, arg_int, APTR(&G.lo0), _("only long arg 0 (int)")},
|
||||
// for short-only options long option can be NULL
|
||||
{NULL, NEED_ARG, NULL, '0', arg_string, APTR(&G.so1), _("only short arg 1 (string)")},
|
||||
// if you change `arg_int` to `arg_none`, value will be incremented each `-h`
|
||||
@@ -71,7 +73,7 @@ static sl_option_t cmdlnopts[] = {
|
||||
{"Int", MULT_PAR, NULL, 'I', arg_int, APTR(&G.intarr), _("integer parameter")},
|
||||
{"Dbl", MULT_PAR, NULL, 'D', arg_double, APTR(&G.dblarr), _("double parameter")},
|
||||
{"Str", MULT_PAR, NULL, 'S', arg_string, APTR(&G.strarr), _("string parameter")},
|
||||
{"lo1", NEED_ARG, NULL, 0, arg_int, APTR(&G.lo1), _("only long arg 1 (int)")},
|
||||
{"long1", NEED_ARG, NULL, 0, arg_int, APTR(&G.lo1), _("only long arg 1 (int)")},
|
||||
end_option
|
||||
};
|
||||
|
||||
|
||||
@@ -93,9 +93,9 @@ int main(int argc, char *argv[]){
|
||||
printf("String[%d]: \"%s\"\n", i, *p++);
|
||||
}
|
||||
}
|
||||
if(GP->lo0 != INT_MIN) printf("You set lo0 to %d\n", GP->lo0);
|
||||
if(GP->lo1 != INT_MIN) printf("You set lo1 to %d\n", GP->lo1);
|
||||
if(GP->lo2 != INT_MIN) printf("You set lo2 to %d\n", GP->lo2);
|
||||
if(GP->lo0 != INT_MIN) printf("You set long 0 to %d\n", GP->lo0);
|
||||
if(GP->lo1 != INT_MIN) printf("You set long 1 to %d\n", GP->lo1);
|
||||
if(GP->lo2 != INT_MIN) printf("You set long 2 to %d\n", GP->lo2);
|
||||
if(GP->so1){
|
||||
sl_remove_quotes(GP->so1);
|
||||
printf("String so1=%s\n", GP->so1);
|
||||
|
||||
@@ -8,7 +8,7 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-03-04 17:48+0300\n"
|
||||
"POT-Creation-Date: 2026-03-31 11:35+0300\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
@@ -36,7 +36,7 @@ msgstr ""
|
||||
msgid "Configuration file options (format: key=value):\n"
|
||||
msgstr ""
|
||||
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:69
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:70
|
||||
#, c-format
|
||||
msgid ""
|
||||
"\n"
|
||||
@@ -44,11 +44,11 @@ msgid ""
|
||||
msgstr ""
|
||||
|
||||
#. error reading self name
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:117
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:95
|
||||
msgid "Can't read self name"
|
||||
msgstr ""
|
||||
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:141
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:119
|
||||
msgid "Can't open PID file"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
msgid ""
|
||||
msgstr "Project-Id-Version: PACKAGE VERSION\n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2026-03-04 17:30+0300\n"
|
||||
"POT-Creation-Date: 2026-03-31 11:31+0300\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
@@ -35,7 +35,7 @@ msgstr "sl_conf_showhelp():
|
||||
msgid "Configuration file options (format: key=value):\n"
|
||||
msgstr "ïÐÃÉÉ ËÏÎÆÉÇÕÒÁÃÉÏÎÎÏÇÏ ÆÁÊÌÁ (ÆÏÒÍÁÔ: ËÌÀÞ=ÚÎÁÞÅÎÉÅ):\n"
|
||||
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:69
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:70
|
||||
#, c-format
|
||||
msgid "\n"
|
||||
"Found running process (pid=%d), exit.\n"
|
||||
@@ -43,11 +43,11 @@ msgstr "\n"
|
||||
"ïÂÎÁÒÕÖÅÎ ÏÄÎÏÉÍÅÎÎÙÊ ÐÒÏÃÅÓÓ (pid=%d), ×ÙÈÏÄ.\n"
|
||||
|
||||
#. error reading self name
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:117
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:95
|
||||
msgid "Can't read self name"
|
||||
msgstr "îÅ ÍÏÇÕ ÐÒÏÞÅÓÔØ ÉÍÑ ÐÒÏÃÅÓÓÁ"
|
||||
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:141
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/daemon.c:119
|
||||
msgid "Can't open PID file"
|
||||
msgstr "îÅ ÍÏÇÕ ÏÔËÒÙÔØ PID ÆÁÊÌ"
|
||||
|
||||
@@ -236,5 +236,3 @@ msgstr "
|
||||
#: /home/eddy/Docs/SAO/C_diff/snippets_library/usefull_macros.c:331
|
||||
msgid "Can't setup console"
|
||||
msgstr "îÅ ÍÏÇÕ ÎÁÓÔÒÏÉÔØ ËÏÎÓÏÌØ"
|
||||
|
||||
#, c-format
|
||||
|
||||
39
parseargs.c
39
parseargs.c
@@ -30,6 +30,9 @@
|
||||
#include <ctype.h> // isalpha
|
||||
#include "usefull_macros.h"
|
||||
|
||||
// check `val` field: if it's <33 || >127 - it's just ordered number, not short option
|
||||
#define CHKOPTVAL(Oval) ((Oval) > 32 && (Oval) < 128)
|
||||
|
||||
const char *helpstring = NULL; // will be inited later, can't init with gettext on this stage
|
||||
|
||||
/**
|
||||
@@ -124,18 +127,33 @@ static int get_optind(const char *key, int opt, sl_option_t *options, void (*hel
|
||||
int oind = 0, theopt = opt;
|
||||
sl_option_t *opts = options;
|
||||
assert(opts);
|
||||
//printf("key: %s\n", key);
|
||||
// `opt` should be ':' for "missed arguments", '?' for "not found" and short flag if found and checked
|
||||
if(opt == '?'){ // not found
|
||||
fprintf(stderr, _("No such parameter: `%s`\n"), key);
|
||||
helpfun(-1, options);
|
||||
return -1; // never reached until `helpfun` changed
|
||||
}else if(opt == ':') theopt = optopt; // search to show helpstring "need parameter"
|
||||
for(oind = 0; opts->help && opts->val != theopt; oind++, opts++){
|
||||
DBG("cmp %c and %c", theopt, opts->val);
|
||||
if(key[1] != '-'){ // search by unique short option
|
||||
//printf("Short %c\n", theopt);
|
||||
for(oind = 0; opts->help && opts->val != theopt; oind++, opts++){
|
||||
DBG("cmp %c and %c", theopt, opts->val);
|
||||
}
|
||||
}else{ // search by long option
|
||||
key += 2;
|
||||
int l = strlen(key);
|
||||
for(oind = 0; opts->help; oind++, opts++){
|
||||
//printf("comp %s and %s\n", key, opts->name);
|
||||
if(opts->name && 0 == strncmp(key, opts->name, l)) break;
|
||||
}
|
||||
}
|
||||
if(!opts->help){
|
||||
//printf("Not found\n");
|
||||
return -1;
|
||||
}
|
||||
if(!opts->help) return -1;
|
||||
if(opt == ':'){
|
||||
fprintf(stderr, _("Parameter `%s` needs value\n"), key);
|
||||
if(options[oind].name) fprintf(stderr, _("Parameter `--%s` needs value\n"), options[oind].name);
|
||||
else fprintf(stderr, _("Parameter `-%c` needs value\n"), options[oind].val);
|
||||
helpfun(oind, options);
|
||||
return -1; // never reached until `helpfun` changed
|
||||
}
|
||||
@@ -249,7 +267,7 @@ void sl_parseargs_hf(int *argc, char ***argv, sl_option_t *options, void (*helpf
|
||||
loptr->flag = opts->flag;
|
||||
loptr->val = opts->val;
|
||||
// fill short options if they are:
|
||||
if(!opts->flag && opts->val){
|
||||
if(!opts->flag && CHKOPTVAL(opts->val)){
|
||||
shortlist[i] = (char) opts->val;
|
||||
*soptr++ = opts->val;
|
||||
if(loptr->has_arg) // add ':' if option has required argument
|
||||
@@ -371,21 +389,22 @@ void sl_parseargs(int *argc, char ***argv, sl_option_t *options){
|
||||
|
||||
/**
|
||||
* @brief argsort - compare function for qsort
|
||||
* first - sort by short options; second - sort arguments without sort opts (by long options)
|
||||
* first - sort by short options; second - sort arguments without short opts (by long options)
|
||||
*/
|
||||
static int argsort(const void *a1, const void *a2){
|
||||
const sl_option_t *o1 = (sl_option_t*)a1, *o2 = (sl_option_t*)a2;
|
||||
const char *l1 = o1->name, *l2 = o2->name;
|
||||
int s1 = o1->val, s2 = o2->val;
|
||||
int chk1 = CHKOPTVAL(s1), chk2 = CHKOPTVAL(s2);
|
||||
int *f1 = o1->flag, *f2 = o2->flag;
|
||||
// check if both options has short arg
|
||||
if(f1 == NULL && f2 == NULL && s1 && s2){ // both have short arg
|
||||
if(f1 == NULL && f2 == NULL && chk1 && chk2){ // both have short arg
|
||||
return (s1 - s2);
|
||||
}else if((f1 != NULL || !s1) && (f2 != NULL || !s2)){ // both don't have short arg - sort by long
|
||||
}else if((f1 != NULL || !chk1) && (f2 != NULL || !chk2)){ // both don't have short arg - sort by long
|
||||
assert(l1); assert(l2); // no way to omit long option if short is absent
|
||||
return strcmp(l1, l2);
|
||||
}else{ // only one have short arg -- return it
|
||||
if(f2 || !s2) return -1; // a1 have short - it is 'lesser'
|
||||
if(f2 || !chk2) return -1; // a1 have short - it is 'lesser'
|
||||
else return 1;
|
||||
}
|
||||
}
|
||||
@@ -394,7 +413,7 @@ static int argsort(const void *a1, const void *a2){
|
||||
static void pr_helpstring(sl_option_t *opt, char *buf, int indent, size_t bufsz){
|
||||
size_t p = sprintf(buf, " "); // a little indent
|
||||
int havelongopt = opt->name && *opt->name;
|
||||
if(!opt->flag && opt->val){ // .val is short argument
|
||||
if(!opt->flag && CHKOPTVAL(opt->val)){ // .val is short argument
|
||||
p += snprintf(buf+p, bufsz-p, "-%c", opt->val);
|
||||
if(havelongopt) p += snprintf(buf+p, bufsz-p, ", "); // show comma only it there's shor arg
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user