Sollertis Sollertis - 1 month ago 6
C Question

creating .mid file: writing a '\n' causes '\r\n' in Windows

I have created a

.mid
file by writing bytes to a file and save it as
.midi
. I can run it and it works, but there are some special cases where it does not.

If I write a byte containing
\n
(ASCII
10
) then it will instead write 2 bytes
\r\n
, which makes the
.mid
not runnable. (This is normal for Windows machine to do, but not desirable in my case.) An example of writing
\n
could be when picking the key which is being represented by
\n
.

Is there a workaround to write
\n
and not
\r\n
or another way to make sure that byte written is ASCII
10
on a Windows machine?

Thanks!

Answer Source

On linux/unix, it doesn't matter whether you specify "wb" or "w" to create a file.

But creating a text file using fopen in windows means that all \n are converted to \r\n, so if you're using this to create binary files, the binary files will be "corrupt" if there are some bytes with value "10" (linefeed)

Simple solution: always use fopen("file.bin","wb") when creating a binary file, on all platforms so your code is portable.