Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83; site hcr.UUCP Path: utzoo!hcr!doug From: doug@hcr.UUCP (Doug Moen) Newsgroups: net.lang.c Subject: portable binary io, or, solving the byte order problem Message-ID: <498@hcr.UUCP> Date: Tue, 4-Oct-83 21:02:32 EDT Article-I.D.: hcr.498 Posted: Tue Oct 4 21:02:32 1983 Date-Received: Tue, 4-Oct-83 22:08:26 EDT Organization: Human Computing Resources, Toronto Lines: 51 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: % [+] where specifies the number of bytes in the integer to be written, and 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.