Random Access with Binary I/O - C File

C examples for File:Binary File

Description

Random Access with Binary I/O

Demo Code

#include <stdio.h>
#include <stdlib.h>
#define ARSIZE 1000/*from   w ww.ja v  a2s  . co m*/

int main()
{
    double numbers[ARSIZE];
    double value;
    const char * file = "numbers.dat";
    int i;
    long pos;
    FILE *iofile;
    
    for(i = 0; i < ARSIZE; i++){
        numbers[i] = 100.0 * i + 1.0 / (i + 1);
    }
    if ((iofile = fopen(file, "wb")) == NULL){
        fprintf(stderr, "Could not open %s for output.\n", file);
        exit(EXIT_FAILURE);
    }
    // write array in binary format to file
    fwrite(numbers, sizeof (double), ARSIZE, iofile);
    fclose(iofile);

    if ((iofile = fopen(file, "rb")) == NULL){
        fprintf(stderr,"Could not open %s for random access.\n", file);
        exit(EXIT_FAILURE);
    }
    printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);

    while (scanf("%d", &i) == 1 && i >= 0 && i < ARSIZE){
        pos = (long) i * sizeof(double); // calculate offset
        fseek(iofile, pos, SEEK_SET);    // go there
        fread(&value, sizeof (double), 1, iofile);
        printf("The value there is %f.\n", value);
    }
    fclose(iofile);
    return 0;
}

Result


Related Tutorials