portable binary io, or, solving the byte order problem

Doug Moen doug at hcr.UUCP
Wed Oct 5 11:02:32 AEST 1983


I've read a number of complaints from people who have run into problems
porting binary files from one machine to another, or sending binary
records across a network.   Sooo...

Here's how you can read and write binary files in a machine
independent fashion, without running into the byte order problem,
and without modifying the C language:

	writeb(stream, format, arguments...)
		FILE *stream;
		char *format;

This is similar to fprintf, except that the arguments are chars,
shorts, ints, or longs, and a conversion specification has the form:
	% <n> [+] <c>
where <n> specifies the number of bytes in the integer to be written,
and <c> is one of C, S, I, or L, meaning that the corresponding argument
is a char, short, int, or long.  Writeb writes out each integer with
a standard byte order (ie, high order byte first, low order byte last).
If the optional '+' is present, it indicates
that the integer is signed, and causes sign extension if the integer
needs to be padded to fill the field width.

There is a corresponding routine, readb(), which works like fscanf.
There are also routines called sreadb() and swriteb() which operate
on buffers instead of file pointers, in the manner of sprintf and sscanf.

Additional features can be added, such as this one:
	struct {
		int x;
		long y;
		char z;
	} foobar;

	writeb(stdout, "%{2I,4L,1C}", &foobar);
which is easier to type than:
	writeb(stdout, "%2I%4L%1C", foobar.x, foobar.y, foobar.z);
Or how about a repetition factor for arrays:
	int x[32];
	writeb(stdout, "%[32]4I", x);
Or even a way to read & write floats and doubles in a machine
independent manner.

It is possible to add the printf(3) conversion specifications to writeb,
as there are no conflicts between the two.

Does anybody think this is a good idea?  (or am I off the mark, or
possibly re-inventing the wheel?)
Are there any further suggestions?  If there is sufficient interest,
I will post a hopefully 'standard' implementation after corresponding
with other people interested in the problem.



More information about the Comp.lang.c mailing list