欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言学习——文件——二进制读写

程序员文章站 2022-05-12 16:29:57
...
#include <cstdio>
#include <cstdlib>

#define ARRAY_SIZE 1000

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

    for (i = 0; i < ARRAY_SIZE; i++) {
        numbers[i] = 100.0 * i + 1.0 / (i + 1);
    }
    if ((pFILE = fopen(file, "wb")) == NULL) {
        fprintf(stderr, "Could not open %s for output.\n", file);
        exit(EXIT_FAILURE);
    }
    fwrite(numbers, sizeof(double), ARRAY_SIZE, pFILE);
    fclose(pFILE);
    if ((pFILE = fopen(file, "rb")) == NULL) {
        fprintf(stderr, "Could not open %s for random access.\n", file);
        exit(EXIT_FAILURE);
    }
    fprintf(stdout, "Enter an index int the range 0-%d", ARRAY_SIZE - 1);
    while (scanf("%d", &i) == 1 && i >= 0 && i < ARRAY_SIZE) {
        pos = (long) i * sizeof(double);
        fseek(pFILE, pos, SEEK_SET);
        fread(&value, sizeof(double), 1, pFILE);
        fprintf(stdout, "The value there is %f.\n", value);
        fprintf(stdout, "Next index (out of range to quit):\n");
    }
    fclose(pFILE);
    puts("Bye!");
    return 0;
}

运行结果:

C语言学习——文件——二进制读写 

参考文献

C Primer Plus

 

相关标签: C语言学习