| 1 |
#ifndef lint
|
| 2 |
static const char RCSid[] = "$Id: portio.c,v 2.14 2006/12/23 17:27:45 greg Exp $";
|
| 3 |
#endif
|
| 4 |
/*
|
| 5 |
* Portable i/o for binary files
|
| 6 |
*
|
| 7 |
* External symbols declared in rtio.h
|
| 8 |
*/
|
| 9 |
|
| 10 |
#include "copyright.h"
|
| 11 |
|
| 12 |
#include "rtio.h"
|
| 13 |
|
| 14 |
#include <math.h>
|
| 15 |
|
| 16 |
#ifdef getc_unlocked /* avoid horrendous overhead of flockfile */
|
| 17 |
#undef getc
|
| 18 |
#undef putc
|
| 19 |
#define getc getc_unlocked
|
| 20 |
#define putc putc_unlocked
|
| 21 |
#endif
|
| 22 |
|
| 23 |
|
| 24 |
void
|
| 25 |
putstr( /* write null-terminated string to fp */
|
| 26 |
char *s,
|
| 27 |
FILE *fp
|
| 28 |
)
|
| 29 |
{
|
| 30 |
do
|
| 31 |
putc(*s, fp);
|
| 32 |
while (*s++);
|
| 33 |
}
|
| 34 |
|
| 35 |
|
| 36 |
void
|
| 37 |
putint( /* write a siz-byte integer to fp */
|
| 38 |
long i,
|
| 39 |
int siz,
|
| 40 |
FILE *fp
|
| 41 |
)
|
| 42 |
{
|
| 43 |
while (siz--)
|
| 44 |
putc((int)(i>>(siz<<3) & 0xff), fp);
|
| 45 |
}
|
| 46 |
|
| 47 |
|
| 48 |
void
|
| 49 |
putflt( /* put out floating point number */
|
| 50 |
double f,
|
| 51 |
FILE *fp
|
| 52 |
)
|
| 53 |
{
|
| 54 |
long m;
|
| 55 |
int e;
|
| 56 |
|
| 57 |
m = frexp(f, &e) * 0x7fffffff;
|
| 58 |
if (e > 127) { /* overflow */
|
| 59 |
m = m > 0 ? (long)0x7fffffff : -(long)0x7fffffff;
|
| 60 |
e = 127;
|
| 61 |
} else if (e < -128) { /* underflow */
|
| 62 |
m = 0;
|
| 63 |
e = 0;
|
| 64 |
}
|
| 65 |
putint(m, 4, fp);
|
| 66 |
putint((long)e, 1, fp);
|
| 67 |
}
|
| 68 |
|
| 69 |
|
| 70 |
char *
|
| 71 |
getstr( /* get null-terminated string */
|
| 72 |
char *s,
|
| 73 |
FILE *fp
|
| 74 |
)
|
| 75 |
{
|
| 76 |
char *cp;
|
| 77 |
int c;
|
| 78 |
|
| 79 |
cp = s;
|
| 80 |
while ((c = getc(fp)) != EOF)
|
| 81 |
if ((*cp++ = c) == '\0')
|
| 82 |
return(s);
|
| 83 |
|
| 84 |
return(NULL);
|
| 85 |
}
|
| 86 |
|
| 87 |
|
| 88 |
long
|
| 89 |
getint( /* get a siz-byte integer */
|
| 90 |
int siz,
|
| 91 |
FILE *fp
|
| 92 |
)
|
| 93 |
{
|
| 94 |
int c;
|
| 95 |
long r;
|
| 96 |
|
| 97 |
if ((c = getc(fp)) == EOF)
|
| 98 |
return(EOF);
|
| 99 |
r = 0x80&c ? -1<<8|c : c; /* sign extend */
|
| 100 |
while (--siz > 0) {
|
| 101 |
if ((c = getc(fp)) == EOF)
|
| 102 |
return(EOF);
|
| 103 |
r <<= 8;
|
| 104 |
r |= c;
|
| 105 |
}
|
| 106 |
return(r);
|
| 107 |
}
|
| 108 |
|
| 109 |
|
| 110 |
double
|
| 111 |
getflt( /* get a floating point number */
|
| 112 |
FILE *fp
|
| 113 |
)
|
| 114 |
{
|
| 115 |
long l;
|
| 116 |
double d;
|
| 117 |
|
| 118 |
l = getint(4, fp);
|
| 119 |
if (l == EOF && feof(fp)) /* EOF? */
|
| 120 |
return((double)EOF);
|
| 121 |
if (l == 0) {
|
| 122 |
getc(fp); /* exactly zero -- ignore exponent */
|
| 123 |
return(0.0);
|
| 124 |
}
|
| 125 |
d = (l + (l > 0 ? .5 : -.5)) * (1./0x7fffffff);
|
| 126 |
return(ldexp(d, (int)getint(1, fp)));
|
| 127 |
}
|