portable C

Started by
2 comments, last by athos_musketeer 20 years, 3 months ago
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.
Advertisement
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.
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.
#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...

This topic is closed to new replies.

Advertisement