title: unix: main() interactive, command line, piping & redirection in C?
body: <p>While there is an easy way of using both <strong>file redirection</strong> and <strong>piping</strong>, as well as interactive user input reading , with <strong><em>main()</em></strong>, as shown in this C code snippet...</p>
  
  <pre class="lang-c prettyprint-override"><code>#define  SIZ 1024
  #include &lt;stdio.h&gt;
  extern void do_something_with_the_array(float *a[], int *n);
  
  int main(int argc, const char * argv[])
  {
      float f[SIZ];
      int k = 0;
      while ((scanf("%f", &amp;f[k]) == 1)&amp;&amp;(k &lt; SIZ)) {
        k++;
      }
      do_something_with_the_array(f, k);
      return 0;
  }
  </code></pre>
  
  <p>… I'm not sure if there is a modern UNIX source compatible and easy way of programmatically achieving any of the three possibilities in a <code>main()</code> in <strong>C</strong>, depending on the context ?</p>
  
  <ul>
  <li>interactive reading of a string of numbers as user input<br></li>
  <li>reading of the same string of numbers as command line arguments<br></li>
  <li>file redirection and piping<br></li>
  </ul>
  
  <p>I understand piping and redirection "belong" to the shell which intercepts the program before it even starts executing, while command line arguments and interactive reading "belong" to the <strong><em>main()</em></strong> itself and therefore there may not be an easy way of doing this.</p>
  
  <p>I see using <strong>stdin</strong> or <strong>file</strong> input or <strong>pipe</strong> input pretty self-explanatory. However, reading command line arguments is a different story. Here's a demo how I usually code it, but it looks kind of heavy-handed and hacked to me. Also, in more complicated scenarios with options, this could become a pretty messy piece of code. I'm also not sure how fail-safe or fool proof this is...</p>
  
  <pre><code>#define  SIZ 1024
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  extern void do_something_with_the_array(float *, int);
  
  int main(int argc, const char * argv[])
  {
      float f[SIZ];
      int k = 0;
      if(argc &gt; 2){
          for(k = 0; k &lt; argc - 1; k++) 
              f[k] = (float)atof(argv[k+1]);
      }
      else while ((scanf("%f", &amp;f[k]) == 1)&amp;&amp;(k &lt; SIZ))
          k++;
  
      do_something_with_the_array(f, k);
      return 0;
  }
  </code></pre>
  
  <p>Thanks in advance!</p>