The program works correctly in Linux, but I get extra characters after the end of file when running in Windows or through Wine. Not garbage but repeated text that was already written. The issue persists whether I write to stdout or a file, but doesn't occur with small files, a few hundred KB is needed.
I nailed down the issue to this function:
static unsigned long read_file(const char *filename, const char **output)
{
struct stat file_stats;
int fdescriptor;
unsigned long file_sz;
static char *file;
fdescriptor = open(filename, O_RDONLY);
if (fdescriptor < 0 || (fstat(fdescriptor ,&file_stats) < 0))
{ printf("Error opening file: %s \n", filename);
return (0);
}
if (file_stats.st_size < 0)
{ printf("file %s reports an Incorrect size", filename);
return (0);
}
file_sz = (unsigned long)file_stats.st_size;
file = malloc((file_sz) * sizeof(*file));
if (!file)
{ printf("Error allocating memory for file %s of size %lu\n", filename, file_sz);
return (0);
}
read(fdescriptor, file, file_sz);
*output = file;
write(STDOUT_FILENO, file, file_sz), exit(1); //this statement added for debugging.
return (file_sz);
}
I can't debug through Wine, much less in windows, but by using printf statements I can tell the file size is correct. The issue is either in the reading or the writing and without a debugger I can't look at the contents of the buffer in memory.
The program was compiled with x86_64-w64-mingw32-gcc, version 8.3. which is the same version of gcc in my system.
At this point I'm just perplexed; I would love to hear any ideas you may have.
Thank you.
Edit: The issue was that fewer bytes were being read than the reported file size and I was writing more than necessary. Thanks to Matt for telling me where to look.