Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First things first, your usage doesn't match your argument checking. According to the usage, you must use one of:</p> <pre><code>head &lt;filename&gt; head &lt;filename&gt; -n &lt;count&gt; </code></pre> <p>In other words, <code>argv[1]</code> is <em>always</em> the filename, <code>argv[2]</code> is the one that needs to be set to <code>-n</code> if there are more than two arguments.</p> <p>Secondly, unless you want to use VLAs (variable length arrays), you should probably just set up a pointer to the filename argument with something like:</p> <pre><code>char *fileName = argv[1]; </code></pre> <p>You don't need to change it at all (you'll just be passing it to <code>fopen</code>, presumably), so it's a waste trying to make another copy.</p> <p>In addition, your <code>if</code> statement is wrong as an <code>or</code>, it should be an <code>and</code>. It's guaranteed that <code>argc</code> will either not be 2 or not be 4, since it can't be both at the same time.</p> <p>I would start with something like:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static int usage (void) { printf ("Usage: head &lt;file&gt;\n"); printf (" or: head &lt;file&gt; -n &lt;number of characters&gt;\n"); return -1; } int main (int argc,char *argv[]) { char *fileName; int lineCount; // Checks if correct arguments if ((argc != 2) &amp;&amp; (argc != 4)) return usage(); if ((argc == 4) &amp;&amp; (strcmp(argv[2], "-n" != 0)) return usage(); // Get file spec and line count fileName = argv[1]; lineCount = (argc == 2) ? 10 : atoi (argv[3]); // or strtol for purists if (linecount &lt; 0) lineCount = 0; // Now go ahead and implement the logic for head. } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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