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

#include 
#include 

#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语言学习——文件——二进制读写_第1张图片 

参考文献

C Primer Plus

 

你可能感兴趣的:(C语言学习)