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?
I guess you are having some undefined behaviour there.
The man page of fwrite says:
But your call
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.
fwriteis 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,
sizemeans the size of a single element.nmembis the number of such elements. For example:A more generic approach is this:
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!