Code: Select all
char buffer[256];
FILE *file = fopen("debug.tmp", "w+b");
size_t bytes_written = fwrite(buffer, 1, 256, file);
size_t bytes_read = fread(buffer, 1, 256, file);
fclose(file);
But in Windows (compiled using gcc) bytes_written is set to 256 and bytes_read is also set to 256! In other words it appears to be reading beyond the 'end of file' without reporting any error or truncating the data. This confuses BBC BASIC and causes any files written to be unexpectedly padded to a multiple of 256 bytes.
My reading of the documentation of fopen, fwrite and fread doesn't suggest that I am relying on undefined behaviour here; I've opened the file for both writing and reading so it should be legitimate to do both, with fread respecting the usual end-of-file semantics (i.e. the value returned being less than the requested count).
Can anybody shed some light on this, and/or suggest a workaround?