用二进制I/O进行随机访问

/* randbin.c --- 用二进制I/O进行随机访问 */
#include<stdio.h>
#include<stdlib.h>
#define ARSIZE 1000//数组元素个数是 ARSIZE, 字符常量

int main(int argc, char *argv[])
{
    double numbers[ARSIZE];//声明数组,
    double value;
    const char *file = "numbers.dat";
    int i;
    long pos;
    FILE *iofile;

    //创建一组double类型的值:填充数组内容
    for (size_t 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);
    }

    //把数组以内容以二进制方式写入文件中
    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);
        //定位文件位置:初始位置偏移 pos个字节
        fseek(iofile, pos, SEEK_SET);
        //读取一个double数据:从定位到的位置开始读一个数据, 
        //注意:stdio.h中的函数共享一个文件缓冲区(读缓冲区,或写缓冲区)
        //因此,上面fseek函数定位的位置 fread继续使用
        fread(&value, sizeof(double), 1, iofile);
        //打印读取到的值到屏幕
        printf("The value there is %f.\n", value);
        //超出范围跳出循环
        printf("Next index (out of range to quit):\n");
    }
    //关闭文件
    fclose(iofile);
    //打印结束信息
    printf("hello world!\n");
    return 0;
}

 

posted on 2023-05-04 15:58  david_helloworld  阅读(24)  评论(0)    收藏  举报

导航