Sams Teach Yourself C in 21 Days

(singke) #1
Using Disk Files 461

16


LISTING16.6 fseek.c. Random file access with fseek()
1: /* Random access with fseek(). */
2:
3: #include <stdlib.h>
4: #include <stdio.h>
5:
6: #define MAX 50
7:
8: int main( void )
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)

INPUT

26 448201x-CH16 8/13/02 11:13 AM Page 461

Free download pdf