#include <stdio.h>
#include <string.h>
static void printDoubleAsBigEndianHexBytes(double x) {
unsigned char buf[sizeof(double)];
size_t i;
memcpy(buf, &x, sizeof(double));
printf("0x");
for (i = 0; i < sizeof(double); ++i) {
printf("%02x", buf[i]);
}
puts("");
}
int main(void) {
const char* const fileName = "sample.dat";
FILE* fp;
double v;
size_t len;
puts("Input a real number:");
if (scanf("%lf", &v) != 1) {
fprintf(stderr, "Failed to read a number from stdin.\n");
return -1;
}
printDoubleAsBigEndianHexBytes(v);
/* ファイルへの書き込み */
fp = fopen(fileName, "wb");
if (fp == NULL) {
fprintf(stderr, "Cannot open \"%s\" in write mode.\n", fileName);
return -1;
}
len = fwrite(&v, sizeof(double), 1, fp);
if (len != 1) {
fclose(fp);
fprintf(stderr, "Failed to write to \"%s\".\n", fileName);
return -1;
}
fclose(fp);
/* ファイルからの読み込み */
fp = fopen(fileName, "rb");
if (fp == NULL) {
fprintf(stderr, "Cannot open \"%s\" in read mode.\n", fileName);
return -1;
}
len = fread(&v, sizeof(double), 1, fp);
if (len != 1) {
fclose(fp);
fprintf(stderr, "Failed to read from \"%s\".\n", fileName);
return -1;
}
fclose(fp);
printf("Read value: %f\n", v);
printDoubleAsBigEndianHexBytes(v);
return 0;
}