编辑代码

/* randbin.c -- 用二进制I/O进行随机访问 */
#include <stdio.h>
#include <stdlib.h>

#define ARSIZE 1000

int main()
{
    double numbers[ARSIZE];
    double value;
    const char * file = "numbers.dat";
    int i;
    long pos;
    FILE *iofile;

    // 创建一组 double类型的值
    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);//退出程序
    }
    // 以二进制格式把数组写入文件
    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)//是否输入成功、是否大于1、是否在最大范围内
    {
        pos = (long) i * sizeof(double); // 计算偏移量
        fseek(iofile, pos, SEEK_SET); // 定位到此处
        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);//关闭文件
    puts("Bye!");
    return 0;
}