Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Use <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html" rel="noreferrer"><code>getopt()</code></a>, or perhaps <a href="http://www.gnu.org/software/libc/manual/html_node/Getopt-Long-Options.html" rel="noreferrer"><code>getopt_long()</code></a>.</p> <pre><code>int iflag = 0; enum { WORD_MODE, LINE_MODE } op_mode = WORD_MODE; // Default set int opt; while ((opt = getopt(argc, argv, "ilw") != -1) { switch (opt) { case 'i': iflag = 1; break; case 'l': op_mode = LINE_MODE; break; case 'w': op_mode = WORD_MODE; break; default: fprintf(stderr, "Usage: %s [-ilw] [file ...]\n", argv[0]); exit(EXIT_FAILURE); } } /* Process file names or stdin */ if (optind &gt;= argc) process(stdin, "(standard input)", op_mode); else { int i; for (i = optind; i &lt; argc; i++) { FILE *fp = fopen(argv[i], "r"); if (fp == 0) fprintf(stderr, "%s: failed to open %s (%d %s)\n", argv[0], argv[i], errno, strerror(errno)); else { process(fp, argv[i], op_mode); fclose(fp); } } } </code></pre> <p>Note that you need to determine which headers to include (I make it 4 that are required), and the way I wrote the <code>op_mode</code> type means you have a problem in the function <code>process()</code> - you can't access the enumeration down there. It's best to move the enumeration outside the function; you might even make <code>op_mode</code> a file-scope variable without external linkage (a fancy way of saying <code>static</code>) to avoid passing it to the function. This code does not handle <code>-</code> as a synonym for standard input, another exercise for the reader. Note that <code>getopt()</code> automatically takes care of <code>--</code> to mark the end of options for you.</p> <p>I've not run any version of the typing above past a compiler; there could be mistakes in it.</p> <hr> <p>For extra credit, write a (library) function:</p> <pre><code>int filter(int argc, char **argv, int idx, int (*function)(FILE *fp, const char *fn)); </code></pre> <p>which encapsulates the logic for processing file name options after the <code>getopt()</code> loop. It should handle <code>-</code> as standard input. Note that using this would indicate that <code>op_mode</code> should be a static file scope variable. The <code>filter()</code> function takes <code>argc</code>, <code>argv</code>, <code>optind</code> and a pointer to the processing function. It should return 0 (EXIT_SUCCESS) if it was able to open all the files and all invocations of the function reported 0, otherwise 1 (or EXIT_FAILURE). Having such a function simplifies writing Unix-style 'filter' programs that read files specified on the command line or standard input.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload