[SOLVED] Do I need to close\free fopencookie? – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by TylerDense

I create a pipe using fopencookie to open file by FILE handle inside gz, how would I need to cleanup? Do I need to close something but resulting handle?

For example there’s a bz inside gz:

int do_close(void* f){
    return ::gzclose( reinterpret_cast<gzFile>(cookie) ) ;
}

void main()
{
    cookie_io_functions_t func = {
        NULL,
        NULL,
        NULL,
        do_close
    };

    gzFile gzf = ::gzopen("test.gz", "r");

    FILE* fp = fopencookie(gzf , "r", func);

    BZFILE *bzf = BZ2_bzopen(fp , "r");

    BZ2_bzclose(bzf); 
//Do I need to close something but this?
//If this is not the end of program but is the end of file usage?
}



Solution

I don’t see it explicitly specified in the documentation, but it seems clear that, given it returns a FILE *, it’s expected that you call plain fclose for cleanup, which in turn will call your do_close.

OTOH from what I see in the sources BZ2_bzclose does close automatically the underlying FILE * associated with the BZFILE * calling fclose, so no extra fclose seems to be needed for your code…

… but looking at bzlib.h, I see that BZ2_bzopen is supposed to take a const char *, not a FILE *, so it doesn’t seem correct at all. Probably you want to call BZ2_bzReadOpen instead? In that case, though, the cleanup function you are expected to call (BZ2_bzReadClose) doesn’t call fclose, and you are supposed to do that on your own.


This Question was asked in StackOverflow by TylerDense and Answered by Matteo Italia It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?