Skip to main content
gamedev.net
🔒 Locked

portable C

Started by athos_musketeer 2 replies 700+ views
Original Post
athos_musketeer
athos_musketeer
hi guys i want to know how to write to file a size_t variable and then read it. but i do NOT want to do this.
int i=980;
write(fd, &i, sizeof(i));
[\source]

i want a portable way.
thanks a lot.
C-Junkie
C-Junkie
That''s not portable?

Oh! You''re talking byte sex.

Well, you could always use the network functions like

long i = hton(923);
write(fd,&i,sizeof(i));
...
read(fd,&i,sizeof(i));
i = ntoh(i);

Or write your own endianness converter.
athos_musketeer
athos_musketeer
i''m trying this, but this is not working.


int num=90;
char buf[4];
for( int i = 0; i < 4; i++ )
buf[j] = (num >> (i*8)) &0xff;
write( fd, buf, sizeof( buf));

/*for reading*/
read( fd, buf, sizeof( buf ));
num = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);



the hton* functions are not portable either, if int isn''t exactly 4 bytes long it could crash. or that is what i read.
aboeing
aboeing

#define NetRead32(areap) \
((((BYTE *)areap)[0] << 24) | (((BYTE *)areap)[1] << 16) | \
(((BYTE *)areap)[2] << 8) | ((BYTE *)areap)[3] << 0)

#define NetWrite32(value, areap) \
do \
{ \
BYTE *area = (BYTE *)(areap); \
area[0] = (BYTE)((value >> 24) & 0xFF); \
area[1] = (value >> 16) & 0xFF; \
area[2] = (value >> 8) & 0xFF; \
area[3] = value & 0xFF; \
} while ( 0 )


and soforth for whatever sized things. i now use templates for this purposes.

I hope you never intend to store floats, as you may decide to shoot someone when you do. if you are planning on, there is an excelent 32bit float support library available somewhere from apple, supports almost everything under the sun - works on every platform ive tried it on...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.