printf() problem

AthanasiosTom Zougas zougas at me.utoronto.ca
Wed Apr 26 23:22:30 AEST 1989


In article <11657 at hodge.UUCP> jdm at hodge.UUCP (jdm) writes:
>
>    Perhaps someone could explain this printf() phenomena to me.
>
>    I have a file with binary data.  I want to read four consecutive
>    bytes from the file and display them with printf().  The data
>    in in the file in hex is:
>
>        92 AB 4E 33
>
>    I fopen() the file in binary mode and used the following line
>    of code to read and print out the data:
>
>        printf("%x %x %x %x\n", getc(fp), getc(fp), getc(fp), getc(fp));
>
>    Although the order of the data in the file is:
>
>        92 AB 4E 33
>
>    printf() displays it as:
>
>        33 4E AB 92
>
>    Just the reverse of its order in the file.
>

C puts its function parameters on the stack in "reverse" order, i.e.
the last item is on top (this allows variable number of parameters
for user defined functions). Thus, the last item is accessed FIRST. So
what is happening is the last getc(fp) is called first and hence the
reversal.

>    Changing the code to:
>
>        a = getc(fp);
>        b = getc(fp);
>        c = getc(fp);
>        d = getc(fp);
>
>        printf("%x %x %x %x\n", a, b, c, d);
>
>    solves the problem, but why did printf() screw the order up when
>    I used getc() directly?  How might I correct this?

What you did will correct it. Or try:

	for ( i = 0; i < 4; ++i ) {
	    printf( "%x ", getc(fp) );
	}
	printf( "\n" );

Of course, where you are gaining in not having to declare 4 variables,
you are losing in 5 calls of printf. Trade-offs, trade-offs ...

>
>    This happens in both Turbo C 2.0 and MS C 5.1.

It would happen in any C.

Tom.

-- 
This is my signature:

	tom zougas




More information about the Comp.lang.c mailing list