how to write () a constant?

Chris Torek chris at mimsy.umd.edu
Mon Jan 8 18:36:16 AEST 1990


In article <10883 at attctc.Dallas.TX.US> bobc at attctc.Dallas.TX.US
(Bob Calbridge) writes:
>A quick question if you please,  Suppose you want to write a binary constant
>to a file.  Would the following code be valid?
>
>	write(handle, (int *) '0x01', sizeof(int))

Not in C in general.  In C on a Unix machine, or a machine with Unix
compatible system calls, definitely not.  On a machine without a `write'
library routine / system call, the code would call an undefined function.

(Remember, this is `comp.lang.c', not `comp.lang.c.on.unix' nor
`comp.lang.c.on.ibm-pc' nor any other such thing.)

The best way to write constants to files is to write them in a printable
representation, unless there is some overriding reason (such as backwards
compatibility or---*after* testing, profiling, and tuning---insufficent
speed) to do otherwise.  The only `portable' way to write a binary value
is exemplified by the code

	int val = 1234;
	if (fwrite((void *)&val, sizeof(val), 1, stream)) != sizeof(val))
		... handle error ...

Unix and compatible systems may also provide `getw' and `putw'.  Note
that the order of bytes in the resulting file is machine dependent (and
perhaps even runtime system dependent).

>If so, is there any advantage to it in terms of program size, speed?

In most cases, there is a definite disadvantage in speed in avoiding stdio.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list