randbin.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* randbin.c -- random access, binary i/o */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #define ARSIZE 1000
  5. int main()
  6. {
  7. double numbers[ARSIZE];
  8. double value;
  9. const char * file = "numbers.dat";
  10. int i;
  11. long pos;
  12. FILE *iofile;
  13. // create a set of double values
  14. for(i = 0; i < ARSIZE; i++)
  15. numbers[i] = 100.0 * i + 1.0 / (i + 1);
  16. // attempt to open file
  17. if ((iofile = fopen(file, "wb")) == NULL)
  18. {
  19. fprintf(stderr, "Could not open %s for output.\n", file);
  20. exit(EXIT_FAILURE);
  21. }
  22. // write array in binary format to file
  23. fwrite(numbers, sizeof (double), ARSIZE, iofile);
  24. fclose(iofile);
  25. if ((iofile = fopen(file, "rb")) == NULL)
  26. {
  27. fprintf(stderr,
  28. "Could not open %s for random access.\n", file);
  29. exit(EXIT_FAILURE);
  30. }
  31. // read selected items from file
  32. printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);
  33. while (scanf("%d", &i) == 1 && i >= 0 && i < ARSIZE)
  34. {
  35. pos = (long) i * sizeof(double); // calculate offset
  36. fseek(iofile, pos, SEEK_SET); // go there
  37. fread(&value, sizeof (double), 1, iofile);
  38. printf("The value there is %f.\n", value);
  39. printf("Next index (out of range to quit):\n");
  40. }
  41. // finish up
  42. fclose(iofile);
  43. puts("Bye!");
  44. return 0;
  45. }