title: how to print first 10 lines of a text file using Unix system calls?
body: <p>I want to write my own version of the <code>head</code> Unix command, but my program is not working.</p>
  
  <p>I am trying to to print the first 10 lines of a text file, but instead the program prints all the lines. I specify the file name and number of lines to print via command-line arguments. I am only required to use Unix system calls such as <code>read()</code>, <code>open()</code> and <code>close()</code>.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#include "stdlib.h"
  #include "stdio.h"
  #include &lt;fcntl.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  
  #define BUFFERSZ 256
  #define LINES 10
  
  void fileError( char*, char* );
  
  int main( int ac, char* args[] )
  {
      char buffer[BUFFERSZ];
      int linesToRead = LINES;
      int in_fd, rd_chars;
  
      // check for invalid argument count
      if ( ac &lt; 2 || ac &gt; 3 )
      {
          printf( "usage:  head FILE [n]\n" );
          exit(1);
      }
  
      // check for n
      if ( ac == 3 )
          linesToRead = atoi( args[2] );
  
      // attempt to open the file
      if ( ( in_fd = open( args[1], O_RDONLY ) ) == -1 )
           fileError( "Cannot open ", args[1] );
  
      int lineCount = 0;
  
      //count no. of lines inside file
      while (read( in_fd, buffer, 1 ) == 1) 
      {        
          if ( *buffer == '\n' )
          {
             lineCount++;
          }
      }
      lineCount = lineCount+1;
  
      printf("Linecount: %i\n", lineCount);
  
      int Starting = 0, xline = 0;
  
      // xline = totallines - requiredlines
      xline = lineCount - linesToRead;
      printf("xline: %i \n\n",xline);
  
      if ( xline &lt; 0 )
          xline = 0;
  
      // count for no. of line to print
      int printStop = lineCount - xline;
      printf("printstop: %i \n\n",printStop);
  
      if ( ( in_fd = open( args[1], O_RDONLY ) ) == -1 )
          fileError( "Cannot open ", args[1] );
  
      //read and print till required number
      while (Starting != printStop) {
          read( in_fd, buffer, BUFFERSZ );
          Starting++;    //increment starting
      }
  
      //read( in_fd, buffer, BUFFERSZ );
      printf("%s \n", buffer);
  
      if ( close( in_fd ) == -1 )
          fileError( "Error closing files", "" );
      return 0;
  }
  
  void fileError( char* s1, char* s2 )
  {
      fprintf( stderr, "Error: %s ", s1 );
      perror( s2 );
      exit( 1 );
  }
  </code></pre>
  
  <p>What am I doing wrong?</p>