Re: A loop with C struct

From: Barry Schwarz (schwarzb_at_deloz.net)
Date: 10/31/04


Date: Sat, 30 Oct 2004 17:05:45 -0700

On 22 Oct 2004 13:09:58 -0700, ronenk@tauex.tau.ac.il (Ronen Kfir)
wrote:

>Thank You for tour response!
>I have read it all & learned from it.
>this is the loop I put instead of the original one:
>
>while (1 == fread(crnt, size, 1, FPcrnt))
> {
> rewind(FPprev);
> while (1 == fread(prev, size, 1, FPprev))
> {
>
> if (crnt->ID!=prev->ID)
>
> fwrite (crnt, size, 1, FPNewMbr);
> }
> }
>
>
>Output I get is allways he content of crnt * 5.
>Why is that so?!

In your data, the third block of FPprev is equal to the first block of
FPcrnt and the fourth through sixth blocks of each are set to zeros.

In your outer loop above, you read the first block of FPcrnt.

In the inner loop:

        You read the first block of FPprev.
        The if evaluates to true
        You write the first block of FPcrnt to FPNewMbr
        You read the second block of FPprev.
        The if evaluates to true
        You write the first block of FPcrnt to FPNewMbr again
        You read the third block of FPprev.
        The if evaluates to false
        You read the fourth block of FPprev.
        The if evaluates to true
        You write the first block of FPcrnt to FPNewMbr again
        etc

As you can see, you write the FPcrnt block to FPNewMbr whenever it
doesn't match the current block of FPprev. This is guaranteed to
occur a minimum of five times (six if there is no corresponding FPprev
block).

You should only write the FPcrnt block to FPNewMbr whenever it doesn't
match every block of FPprev.

One solution is to change your if from != to == and iterate the outer
loop when it evaluates to true. If you ever exit the inner loop
normally, then you know that every block mismatched and you should
write to FPNewMbr.

<<Remove the del for email>>