Example (lseek -- Move File Pointer)

This example opens the file sample.dat and, if successful, moves the file pointer to the eighth position in the file. The example then attempts to read bytes from the file, starting at the new pointer position, and reads them into the buffer.

#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
int main(void)
{
   long length;
   int fh;
   char buffer[20];
   memset(buffer, '\0', 20);               /* Initialize the buffer           */
   printf("\nCreating sample.dat.\n");
   system("echo Sample Program > sample.dat");
   if (-1 == (fh = open("sample.dat", O_RDWR|O_APPEND))) {
      perror("Unable to open sample.dat.");
      exit(EXIT_FAILURE);
   }
   if (-1 == lseek(fh, 7, SEEK_SET)) {     /* place the file pointer at the   */
      perror("Unable to lseek");           /* eighth position in the file     */
      close(fh);
      return EXIT_FAILURE;
   }
   if (8 != read(fh, buffer, 8)) {
      perror("Unable to read from sample.dat.");
      close(fh);
      return EXIT_FAILURE;
   }
   printf("Successfully read in the following:\n%s.\n", buffer);
   close(fh);
   return 0;
   /****************************************************************************
      The output should be:
      Creating sample.dat.
      Successfully read in the following:
      Program .
   ****************************************************************************/
}