Search code examples
c++mfcfwrite

Unable to write using fwrite()


I'm using fwrite in an MFC application to print content of lBuffer as shown in following C++ code:

PvBuffer *lBuffer = NULL;

// Retrieve next buffer     
PvResult lResult = lStream.RetrieveBuffer(&lBuffer, &lOperationResult, 1000);
if (lResult.IsOK())
{
    FILE *fp = fopen("C:\\Users\\acm45\\Desktop\\abuffer.bin", "wb");
    fwrite(lBuffer, 1, 10075968, fp);
    fclose(fp);
}

Any idea why the content of the file abuffer.bin is always empty even though IResult returns success?
Note the file is always created when I run the program, but it is empty and size is 0KB.

Update:
To debug I did this:

FILE *fp = fopen("C:\\Users\\acm45\\Desktop\\abuffer.bin", "wb");
if (fp) {
    fwrite(lBuffer, 1,10075968, fp);
    fclose(fp);
} else {
    printf("error opening file");
}

and the output did not print "error opening file", but still the file is empty. What do I do now?


Solution

  • I guess you are having some undefined behaviour there.

    The man page of fwrite says:

    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

    The function fwrite() writes nmemb elements of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

    But your call

    lStream.RetrieveBuffer( &lBuffer, &lOperationResult, 1000 );
    

    lets me guess you don't have 10075968 elements with each one byte long.

    Also: Is your buffer a collection of POD elements? If not, that's another reason for undefined behaviour. fwrite is only for POD types.

    Generally, it is better to use C++ streams.


    addendum to explain fwrite

    size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

    Here, size means the size of a single element.

    nmemb is the number of such elements. For example:

    ...
    struct Foobar {
        int frob;
    };
    
    int main () {
        ...
        Foobar thingies[5];
        fwrite (thingies, sizeof(Foobar), 5, some_file);
    }
    

    A more generic approach is this:

        Foobar thingies[5];
        const size_t nm = sizeof(thingies) / sizeof(Foobar);
        fwrite (thingies, sizeof(Foobar), nm, some_file);
    

    This read: "size of the array, divided by size of a single element, which equals the number of elements in that array".

    But note that this only works for arrays, not pointers!

        Foobar *thingies = new Foobar[5];
        const size_t nm = sizeof(thingies) / sizeof(Foobar);
        fwrite (thingies, sizeof(Foobar), nm, some_file);
        // THIS IS WRONG. sizeof(thingies) now equals to the
        // size of a pointer!