--- ray/src/common/portio.c 2012/10/19 01:40:33 2.15 +++ ray/src/common/portio.c 2021/02/19 16:15:23 2.25 @@ -1,5 +1,5 @@ #ifndef lint -static const char RCSid[] = "$Id: portio.c,v 2.15 2012/10/19 01:40:33 greg Exp $"; +static const char RCSid[] = "$Id: portio.c,v 2.25 2021/02/19 16:15:23 greg Exp $"; #endif /* * Portable i/o for binary files @@ -13,15 +13,8 @@ static const char RCSid[] = "$Id: portio.c,v 2.15 2012 #include -#ifdef getc_unlocked /* avoid horrendous overhead of flockfile */ -#undef getc -#undef putc -#define getc getc_unlocked -#define putc putc_unlocked -#endif - -void +int putstr( /* write null-terminated string to fp */ char *s, FILE *fp @@ -29,23 +22,32 @@ putstr( /* write null-terminated string to fp */ { do putc(*s, fp); - while (*s++); + while (*++s); + + return(putc(0, fp)); /* terminator */ } -void +int putint( /* write a siz-byte integer to fp */ long i, int siz, FILE *fp ) { - while (siz--) - putc((int)(i>>(siz<<3) & 0xff), fp); + while (siz > sizeof(long)) { + putc((i<0)*0xff, fp); + siz--; + } + siz <<= 3; + while ((siz -= 8) > 0) + putc((int)(i>>siz & 0xff), fp); + + return(putc((int)(i & 0xff), fp) == EOF ? EOF : 0); } -void +int putflt( /* put out floating point number */ double f, FILE *fp @@ -63,10 +65,31 @@ putflt( /* put out floating point number */ e = 0; } putint(m, 4, fp); - putint((long)e, 1, fp); + return(putint(e, 1, fp)); } +size_t +putbinary( /* fwrite() replacement for small objects */ + const void *p, + size_t elsiz, + size_t nel, + FILE *fp) +{ + const char *s = (const char *)p; + size_t nbytes = elsiz*nel; + + if (nbytes > 128) + return(fwrite(p, elsiz, nel, fp)); + + while (nbytes-- > 0) + if (putc(*s++, fp) == EOF) + return((elsiz*nel - nbytes)/elsiz); + + return(nel); +} + + char * getstr( /* get null-terminated string */ char *s, @@ -96,7 +119,9 @@ getint( /* get a siz-byte integer */ if ((c = getc(fp)) == EOF) return(EOF); - r = 0x80&c ? -1<<8|c : c; /* sign extend */ + r = c; + if (c & 0x80) /* sign extend? */ + r |= -256L; while (--siz > 0) { if ((c = getc(fp)) == EOF) return(EOF); @@ -124,4 +149,27 @@ getflt( /* get a floating point number */ } d = (l + (l > 0 ? .5 : -.5)) * (1./0x7fffffff); return(ldexp(d, (int)getint(1, fp))); +} + + +size_t +getbinary( /* fread() replacement for small objects */ + void *p, + size_t elsiz, + size_t nel, + FILE *fp) +{ + char *s = (char *)p; + size_t nbytes = elsiz*nel; + int c; + + if (nbytes > 128) + return(fread(p, elsiz, nel, fp)); + + while (nbytes-- > 0) { + if ((c = getc(fp)) == EOF) + return((elsiz*nel - nbytes)/elsiz); + *s++ = c; + } + return(nel); }