Skip to content

Instantly share code, notes, and snippets.

@exelotl
Created September 30, 2019 01:34
Show Gist options
  • Save exelotl/d286002d8f90f75bbd4543352e271f73 to your computer and use it in GitHub Desktop.
Save exelotl/d286002d8f90f75bbd4543352e271f73 to your computer and use it in GitHub Desktop.
proc c_fputc(c: char, f: File): cint {.
importc: "fputs", header: "<stdio.h>", tags: [WriteIOEffect].}
# ...
when defined(windows):
proc writeWindows(f: File; s: string; doRaise = false) =
# Don't ask why but the 'printf' family of function is the only thing
# that writes utf-8 strings reliably on Windows. At least on my Win 10
# machine. We also enable `setConsoleOutputCP(65001)` now by default.
# But we cannot call printf directly as the string might contain \0.
# So we have to loop over all the sections separated by potential \0s.
var i = c_fprintf(f, "%s", s)
while i < s.len:
if s[i] == '\0':
let c = c_fputc('\0', f)
if c != 0:
if doRaise: raiseEIO("cannot write string to file")
break
inc i
else:
let w = c_fprintf(f, "%s", unsafeAddr s[i])
if w <= 0:
if doRaise: raiseEIO("cannot write string to file")
break
inc i, w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment