home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list16_6.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-10-16  |  1.7 KB  |  75 lines

  1.  /* Random access with fseek(). */
  2.  
  3.  #include <stdio.h>
  4.  #include <io.h>
  5.  
  6.  #define MAX 50
  7.  
  8.  main()
  9.  {
  10.      FILE *fp;
  11.      int data, count, array[MAX];
  12.      long offset;
  13.  
  14.      /* Initialize the array. */
  15.  
  16.      for (count = 0; count < MAX; count++)
  17.          array[count] = count * 10;
  18.  
  19.      /* Open a binary file for writing. */
  20.  
  21.      if ( (fp = fopen("RANDOM.DAT", "wb")) == NULL)
  22.      {
  23.          fprintf(stderr, "\nError opening file.");
  24.          exit(1);
  25.      }
  26.  
  27.      /* Write the array to the file, then close it. */
  28.  
  29.      if ( (fwrite(array, sizeof(int), MAX, fp)) != MAX)
  30.      {
  31.          fprintf(stderr, "\nError writing data to file.");
  32.          exit(1);
  33.      }
  34.  
  35.      fclose(fp);
  36.  
  37.      /* Open the file for reading. */
  38.  
  39.      if ( (fp = fopen("RANDOM.DAT", "rb")) == NULL)
  40.      {
  41.          fprintf(stderr, "\nError opening file.");
  42.          exit(1);
  43.      }
  44.  
  45.      /* Ask user which element to read. Input the element */
  46.      /* and display it, quitting when -1 is entered. */
  47.  
  48.      while (1)
  49.      {
  50.          printf("\nEnter element to read, 0-%d, -1 to quit: ",MAX-1);
  51.          scanf("%ld", &offset);
  52.  
  53.          if (offset < 0)
  54.              break;
  55.          else if (offset > MAX-1)
  56.              continue;
  57.  
  58.          /* Move the position indicator to the specified element. */
  59.  
  60.          if ( (fseek(fp, (offset*sizeof(int)), SEEK_SET)) != NULL)
  61.          {
  62.              fprintf(stderr, "\nError using fseek().");
  63.              exit(1);
  64.          }
  65.  
  66.          /* Read in a single integer. */
  67.  
  68.          fread(&data, sizeof(int), 1, fp);
  69.  
  70.          printf("\nElement %ld has value %d.", offset, data);
  71.      }
  72.  
  73.      fclose(fp);
  74.  }
  75.