Search code examples
ciofwrite

Why is my function representation not reverse-copying data?


I have this function representation of fwrite that write bytes backwards. However.. it doesn't really copy them backwards which appears to be really strange.

size_t fwrite_backward ( const void * ptr, size_t size, size_t count, FILE * stream )
{
    int i, chr;

    for(i = count * size; i != 0; i--)
    {
        if( fputc(*(unsigned char*)ptr + (count * size) - i, stream) != EOF )
        chr++;
    }
    return chr;
}

It is supposed to behave exactly like fwrite with two differences:

  • It copies data backwards
  • It doesn't set ferror

What i might be doing wrong?


Solution

  • The implementation below seems to work. It also corrects some minor design flaws of your version:

    • Your code writes out all bytes backwards, but you should write all items backwards with the bytes in the items themselves in the original order. (After all, what's the distinction between size and count for?) The code below works with items of any size.

    • Yor code returns the number of bytes written. But fwrite returns the number of items written.

    • The loop ends early on unsuccessful writes.

    So:

    size_t fwrite_rev(const void *ptr, size_t size, size_t count, FILE *stream)
    {
        const unsigned char *p = ptr;
        size_t written = 0;
    
        while (count--) {
            if (fwrite(p + size * count, size, 1, stream) < 1) break;
            written++;
        }
    
        return written;
    }