Mail Archives: djgpp/1996/05/09/09:14:03
From: Rikard Thunberg <thunberg AT algonet DOT se>
Date: Mon, 06 May 1996 23:40:13 +0200
What is the appropriate way to read/write integers from/to a file with the same size as it is stored in
memory, i.e. a long integer (32bit) would occupy 4 bytes in the file. I have reached a solution but it seems
rather clumsy:
#include<stdio.h>
void main()
{
FILE *fileh;
unsigned long my_long=0x41424344;
char *charpek;
fileh = fopen("test.dat","wb");
charpek= (char *) &my_long;
fprintf(fileh,"%c%c%c%c",*charpek,*(charpek+1),*(charpek+2),*(charpek+3));
fclose(fileh);
}
Your right that's UGLY. Try this:
#include<stdio.h>
void main()
{
FILE *fileh;
unsigned long my_long=0x41424344;
short my_short = 123;
fileh = fopen("test.dat","wb");
fwrite( &my_long, sizeof my_long, 1, fileh );
fwrite( &my_short, sizeof my_short, 1, fileh );
fclose(fileh);
}
--
Art S. Kagel, kagel AT quasar DOT bloomberg DOT com
A proverb is no proverb to you 'till life has illustrated it. -- John Keats
- Raw text -