]> git.ozlabs.org Git - ccan/blob - ccan/foreach/_info
c49a9525d9cfc9261be3454f98125b7c8675bbfa
[ccan] / ccan / foreach / _info
1 #include <stdio.h>
2 #include <string.h>
3 #include "config.h"
4
5 /**
6  * foreach - macro for simple iteration of arrays
7  *
8  * The foreach_int and foreach_ptr macros allow simple iteration of
9  * static arrays.  This is very efficient with good compiler support
10  * (ie. gcc), and not too bad (ie. a few compares and mallocs) for
11  * other compilers.
12  *
13  * License: LGPL (3 or any later version)
14  * Author: Rusty Russell <rusty@rustcorp.com.au>
15  *
16  * Example:
17  *      // Figure out how to get usage: message out of a program.
18  *      #include <ccan/foreach/foreach.h>
19  *      #include <stdio.h>
20  *      #include <stdlib.h>
21  *      #include <string.h>
22  *      #include <err.h>
23  *
24  *      // Returns true if program outputs "usage:"
25  *      static bool try_usage(const char *prog, const char *arg)
26  *      {
27  *              char *command;
28  *              FILE *in;
29  *              int status;
30  *
31  *              command = malloc(strlen(prog) + 1 + strlen(arg) + 1 +
32  *                               sizeof("</dev/null 2>&1 | grep -qiw usage:"));
33  *              sprintf(command, "%s %s </dev/null 2>&1 | grep -qiw usage:",
34  *                      prog, arg);
35  *              in = popen(command, "r");
36  *              if (!in)
37  *                      err(2, "running '%s'", command);
38  *              status = pclose(in);
39  *              free(command);
40  *              return (WIFEXITED(status) && WEXITSTATUS(status) == 0);
41  *      }
42  *
43  *      int main(int argc, char *argv[])
44  *      {
45  *              const char *arg;
46  *
47  *              if (argc != 2)
48  *                      errx(1, "Usage: %s <progname>\n"
49  *                           "Figures out how to get usage message", argv[0]);
50  *              foreach_ptr(arg, "--help", "-h", "--usage", "-?", "") {
51  *                      if (try_usage(argv[1], arg)) {
52  *                              printf("%s %s\n", argv[1], arg);
53  *                              exit(0);
54  *                      }
55  *              }
56  *              printf("%s is unhelpful\n", argv[1]);
57  *              exit(1);
58  *      }
59  */
60 int main(int argc, char *argv[])
61 {
62         if (argc != 2)
63                 return 1;
64
65         if (strcmp(argv[1], "depends") == 0) {
66 #if !HAVE_COMPOUND_LITERALS || !HAVE_FOR_LOOP_DECLARATION
67                 printf("ccan/list\n");
68 #endif
69                 return 0;
70         }
71
72         return 1;
73 }