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 Primer Plus
上一篇: 数据库性能优化 _概括
下一篇: 040-struct 结构体(二)