Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

athos_musketeer

portable C

This topic is 5328 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

#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...

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!