Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!uunet!aplcen!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: how to write () a constant? Keywords: how to, write(), constant Message-ID: <21689@mimsy.umd.edu> Date: 8 Jan 90 07:36:16 GMT References: <10883@attctc.Dallas.TX.US> Distribution: na Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 34 In article <10883@attctc.Dallas.TX.US> bobc@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@cs.umd.edu Path: uunet!mimsy!chris