Im reading binary file, storing the data into arrays, and then writing the data into another file. Basicly, a copy. Everything was fine, but then suddenly, out of nowhere, the output file was corrupt. the size of the output is exact like the input, however, if loaded in Quakespasm (Q1 engine) it crashed with Hunk_alloc failed.
proc AddLump*(lumpnum: int32; data: pointer; len: int32) =
var lump: ptr lump_t
lump = addr(header.lumps[lumpnum])
lump.fileofs = c_ftell(wadfile).int32
# lump.fileofs = getFilePos(wadfile).int32
lump.filelen = len
echo header.lumps[lumpnum], " lump.fileofs ", lump.fileofs, " lump.filelen ", lump.filelen
writeBuffer(wadfile.addr, data, (len + 3) and not 3) # this comes from C: fwrite(wadfile, data, (len+3)&~3)
After pulling my hair couple of hous, thinking its some ptr array leak in other procs, it narrowed down to the I/O.
I changed getFilePos with:
proc c_ftell(f: File): int64 {.
importc: "ftell", header: "<stdio.h>", tags: [].}
and everything went back to normal.
However, if I used "_ftelli64" version, the output was same as with getFilePos, empty bytes inbetween blocks, and wrong offsets.
How is this possible, when i didnt touch anything in the read/write procs? I didnt change the compiler, gcc or nim.
My first guess would be that your file might be opened in text mode:
From the MS docs: "The value returned by ftell and _ftelli64 may not reflect the physical byte offset for streams opened in text mode, because text mode causes carriage return-line feed translation. "
I do f = open(filename)
Istrere any way to open it in text mode, or binary?