adds a code sample for UcxMap

Sat, 12 May 2018 14:50:09 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 12 May 2018 14:50:09 +0200
changeset 298
fffe3a16a3de
parent 297
ba760f2195c3
child 299
e7dfcf229625

adds a code sample for UcxMap

docs/src/modules.md file | annotate | diff | comparison | revisions
--- a/docs/src/modules.md	Sat May 12 14:13:53 2018 +0200
+++ b/docs/src/modules.md	Sat May 12 14:50:09 2018 +0200
@@ -279,6 +279,70 @@
 chaining with linked lists. Similarly to the list module, we provide a
 `UCX_MAP_FOREACH` macro to conveniently iterate through the key/value pairs.
 
+### Parsing command line options
+
+Assume you want to parse command line options and record them within a map.
+One way to do this is shown by the following code sample:
+```C
+    UcxMap* options = ucx_map_new(16);
+    const char *NOARG = "";
+    
+    char *option = NULL;
+    char optchar = 0;
+    for(int i=1;i<argc;i++) {
+        char *arg = argv[i];
+        size_t len = strlen(arg);
+        if(len > 1 && arg[0] == '-') {
+            if(option) {
+                fprintf(stderr,
+                        "Missing argument for option -%c\n", optchar);
+                return 1;
+            }
+            for(int c=1;c<len;c++) {
+                switch(arg[c]) {
+                    default: {
+                        fprintf(stderr, "Unknown option -%c\n\n", arg[c]);
+                        return 1;
+                    }
+                    case 'v': {
+                        ucx_map_cstr_put(options, "verbose", NOARG);
+                        break;
+                    }
+                    case 'o': {
+                        option = "output";
+                        optchar = 'o';
+                        break;
+                    }
+                }
+            }
+        } else if(option) {
+            ucx_map_cstr_put(options, option, arg);
+            option = NULL;
+        } else {
+            /* ... handle argument that is not an option ... */
+        }
+    }
+    if(option) {
+        fprintf(stderr,
+                "Missing argument for option -%c\n", optchar);
+        return 1;
+    }
+```
+With the following loop, you can access the previously recorded options:
+```C
+    UcxMapIterator iter = ucx_map_iterator(options);
+    char *arg;
+    UCX_MAP_FOREACH(optkey, arg, iter) {
+        char* opt = optkey.data;
+        if (*arg) {
+            printf("%s = %s\n", opt, arg);
+        } else {
+            printf("%s active\n", opt);
+        }
+    }
+```
+Don't forget to call `ucx_map_free()`, when you are done with the map.
+
 ## Memory Pool
 
 *Header file:* [mempool.h](api/mempool_8h.html)  

mercurial