io.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This is a part of `system.nim`, you should not manually import it.
  10. include inclrtl
  11. import std/private/since
  12. import formatfloat
  13. # ----------------- IO Part ------------------------------------------------
  14. type
  15. CFile {.importc: "FILE", header: "<stdio.h>",
  16. incompleteStruct.} = object
  17. File* = ptr CFile ## The type representing a file handle.
  18. FileMode* = enum ## The file mode when opening a file.
  19. fmRead, ## Open the file for read access only.
  20. fmWrite, ## Open the file for write access only.
  21. ## If the file does not exist, it will be
  22. ## created. Existing files will be cleared!
  23. fmReadWrite, ## Open the file for read and write access.
  24. ## If the file does not exist, it will be
  25. ## created. Existing files will be cleared!
  26. fmReadWriteExisting, ## Open the file for read and write access.
  27. ## If the file does not exist, it will not be
  28. ## created. The existing file will not be cleared.
  29. fmAppend ## Open the file for writing only; append data
  30. ## at the end.
  31. FileHandle* = cint ## type that represents an OS file handle; this is
  32. ## useful for low-level file access
  33. # text file handling:
  34. when not defined(nimscript) and not defined(js):
  35. # duplicated between io and ansi_c
  36. const stdioUsesMacros = (defined(osx) or defined(freebsd) or defined(dragonfly)) and not defined(emscripten)
  37. const stderrName = when stdioUsesMacros: "__stderrp" else: "stderr"
  38. const stdoutName = when stdioUsesMacros: "__stdoutp" else: "stdout"
  39. const stdinName = when stdioUsesMacros: "__stdinp" else: "stdin"
  40. var
  41. stdin* {.importc: stdinName, header: "<stdio.h>".}: File
  42. ## The standard input stream.
  43. stdout* {.importc: stdoutName, header: "<stdio.h>".}: File
  44. ## The standard output stream.
  45. stderr* {.importc: stderrName, header: "<stdio.h>".}: File
  46. ## The standard error stream.
  47. when defined(useStdoutAsStdmsg):
  48. template stdmsg*: File = stdout
  49. else:
  50. template stdmsg*: File = stderr
  51. ## Template which expands to either stdout or stderr depending on
  52. ## `useStdoutAsStdmsg` compile-time switch.
  53. when defined(windows):
  54. proc c_fileno(f: File): cint {.
  55. importc: "_fileno", header: "<stdio.h>".}
  56. else:
  57. proc c_fileno(f: File): cint {.
  58. importc: "fileno", header: "<fcntl.h>".}
  59. when defined(windows):
  60. proc c_fdopen(filehandle: cint, mode: cstring): File {.
  61. importc: "_fdopen", header: "<stdio.h>".}
  62. else:
  63. proc c_fdopen(filehandle: cint, mode: cstring): File {.
  64. importc: "fdopen", header: "<stdio.h>".}
  65. proc c_fputs(c: cstring, f: File): cint {.
  66. importc: "fputs", header: "<stdio.h>", tags: [WriteIOEffect].}
  67. proc c_fgets(c: cstring, n: cint, f: File): cstring {.
  68. importc: "fgets", header: "<stdio.h>", tags: [ReadIOEffect].}
  69. proc c_fgetc(stream: File): cint {.
  70. importc: "fgetc", header: "<stdio.h>", tags: [].}
  71. proc c_ungetc(c: cint, f: File): cint {.
  72. importc: "ungetc", header: "<stdio.h>", tags: [].}
  73. proc c_putc(c: cint, stream: File): cint {.
  74. importc: "putc", header: "<stdio.h>", tags: [WriteIOEffect].}
  75. proc c_fflush(f: File): cint {.
  76. importc: "fflush", header: "<stdio.h>".}
  77. proc c_fclose(f: File): cint {.
  78. importc: "fclose", header: "<stdio.h>".}
  79. proc c_clearerr(f: File) {.
  80. importc: "clearerr", header: "<stdio.h>".}
  81. proc c_feof(f: File): cint {.
  82. importc: "feof", header: "<stdio.h>".}
  83. when not declared(c_fwrite):
  84. proc c_fwrite(buf: pointer, size, n: csize_t, f: File): cint {.
  85. importc: "fwrite", header: "<stdio.h>".}
  86. # C routine that is used here:
  87. proc c_fread(buf: pointer, size, n: csize_t, f: File): csize_t {.
  88. importc: "fread", header: "<stdio.h>", tags: [ReadIOEffect].}
  89. when defined(windows):
  90. when not defined(amd64):
  91. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  92. importc: "fseek", header: "<stdio.h>", tags: [].}
  93. proc c_ftell(f: File): int64 {.
  94. importc: "ftell", header: "<stdio.h>", tags: [].}
  95. else:
  96. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  97. importc: "_fseeki64", header: "<stdio.h>", tags: [].}
  98. when defined(tcc):
  99. proc c_fsetpos(f: File, pos: var int64): int32 {.
  100. importc: "fsetpos", header: "<stdio.h>", tags: [].}
  101. proc c_fgetpos(f: File, pos: var int64): int32 {.
  102. importc: "fgetpos", header: "<stdio.h>", tags: [].}
  103. proc c_telli64(f: cint): int64 {.
  104. importc: "_telli64", header: "<io.h>", tags: [].}
  105. proc c_ftell(f: File): int64 =
  106. # Taken from https://pt.osdn.net/projects/mingw/scm/git/mingw-org-wsl/blobs/5.4-trunk/mingwrt/mingwex/stdio/ftelli64.c
  107. result = -1'i64
  108. var pos: int64
  109. if c_fgetpos(f, pos) == 0 and c_fsetpos(f, pos) == 0:
  110. result = c_telli64(c_fileno(f))
  111. else:
  112. proc c_ftell(f: File): int64 {.
  113. importc: "_ftelli64", header: "<stdio.h>", tags: [].}
  114. else:
  115. proc c_fseek(f: File, offset: int64, whence: cint): cint {.
  116. importc: "fseeko", header: "<stdio.h>", tags: [].}
  117. proc c_ftell(f: File): int64 {.
  118. importc: "ftello", header: "<stdio.h>", tags: [].}
  119. proc c_ferror(f: File): cint {.
  120. importc: "ferror", header: "<stdio.h>", tags: [].}
  121. proc c_setvbuf(f: File, buf: pointer, mode: cint, size: csize_t): cint {.
  122. importc: "setvbuf", header: "<stdio.h>", tags: [].}
  123. proc c_fprintf(f: File, frmt: cstring): cint {.
  124. importc: "fprintf", header: "<stdio.h>", varargs, discardable.}
  125. proc c_fputc(c: char, f: File): cint {.
  126. importc: "fputc", header: "<stdio.h>".}
  127. # When running nim in android app, stdout goes nowhere, so echo gets ignored
  128. # To redirect echo to the android logcat, use -d:androidNDK
  129. when defined(androidNDK):
  130. const ANDROID_LOG_VERBOSE = 2.cint
  131. proc android_log_print(prio: cint, tag: cstring, fmt: cstring): cint
  132. {.importc: "__android_log_print", header: "<android/log.h>", varargs, discardable.}
  133. template sysFatal(exc, msg) =
  134. raise newException(exc, msg)
  135. proc raiseEIO(msg: string) {.noinline, noreturn.} =
  136. sysFatal(IOError, msg)
  137. proc raiseEOF() {.noinline, noreturn.} =
  138. sysFatal(EOFError, "EOF reached")
  139. proc strerror(errnum: cint): cstring {.importc, header: "<string.h>".}
  140. when not defined(nimscript):
  141. var
  142. errno {.importc, header: "<errno.h>".}: cint ## error variable
  143. EINTR {.importc: "EINTR", header: "<errno.h>".}: cint
  144. proc checkErr(f: File) =
  145. when not defined(nimscript):
  146. if c_ferror(f) != 0:
  147. let msg = "errno: " & $errno & " `" & $strerror(errno) & "`"
  148. c_clearerr(f)
  149. raiseEIO(msg)
  150. else:
  151. # shouldn't happen
  152. quit(1)
  153. {.push stackTrace:off, profiler:off.}
  154. proc readBuffer*(f: File, buffer: pointer, len: Natural): int {.
  155. tags: [ReadIOEffect], benign.} =
  156. ## reads `len` bytes into the buffer pointed to by `buffer`. Returns
  157. ## the actual number of bytes that have been read which may be less than
  158. ## `len` (if not as many bytes are remaining), but not greater.
  159. result = cast[int](c_fread(buffer, 1, cast[csize_t](len), f))
  160. if result != len: checkErr(f)
  161. proc readBytes*(f: File, a: var openArray[int8|uint8], start, len: Natural): int {.
  162. tags: [ReadIOEffect], benign.} =
  163. ## reads `len` bytes into the buffer `a` starting at `a[start]`. Returns
  164. ## the actual number of bytes that have been read which may be less than
  165. ## `len` (if not as many bytes are remaining), but not greater.
  166. result = readBuffer(f, addr(a[start]), len)
  167. proc readChars*(f: File, a: var openArray[char]): int {.tags: [ReadIOEffect], benign.} =
  168. ## reads up to `a.len` bytes into the buffer `a`. Returns
  169. ## the actual number of bytes that have been read which may be less than
  170. ## `a.len` (if not as many bytes are remaining), but not greater.
  171. result = readBuffer(f, addr(a[0]), a.len)
  172. proc readChars*(f: File, a: var openArray[char], start, len: Natural): int {.
  173. tags: [ReadIOEffect], benign, deprecated:
  174. "use other `readChars` overload, possibly via: readChars(toOpenArray(buf, start, len-1))".} =
  175. ## reads `len` bytes into the buffer `a` starting at `a[start]`. Returns
  176. ## the actual number of bytes that have been read which may be less than
  177. ## `len` (if not as many bytes are remaining), but not greater.
  178. if (start + len) > len(a):
  179. raiseEIO("buffer overflow: (start+len) > length of openarray buffer")
  180. result = readBuffer(f, addr(a[start]), len)
  181. proc write*(f: File, c: cstring) {.tags: [WriteIOEffect], benign.} =
  182. ## Writes a value to the file `f`. May throw an IO exception.
  183. discard c_fputs(c, f)
  184. checkErr(f)
  185. proc writeBuffer*(f: File, buffer: pointer, len: Natural): int {.
  186. tags: [WriteIOEffect], benign.} =
  187. ## writes the bytes of buffer pointed to by the parameter `buffer` to the
  188. ## file `f`. Returns the number of actual written bytes, which may be less
  189. ## than `len` in case of an error.
  190. result = cast[int](c_fwrite(buffer, 1, cast[csize_t](len), f))
  191. checkErr(f)
  192. proc writeBytes*(f: File, a: openArray[int8|uint8], start, len: Natural): int {.
  193. tags: [WriteIOEffect], benign.} =
  194. ## writes the bytes of `a[start..start+len-1]` to the file `f`. Returns
  195. ## the number of actual written bytes, which may be less than `len` in case
  196. ## of an error.
  197. var x = cast[ptr UncheckedArray[int8]](a)
  198. result = writeBuffer(f, addr(x[int(start)]), len)
  199. proc writeChars*(f: File, a: openArray[char], start, len: Natural): int {.
  200. tags: [WriteIOEffect], benign.} =
  201. ## writes the bytes of `a[start..start+len-1]` to the file `f`. Returns
  202. ## the number of actual written bytes, which may be less than `len` in case
  203. ## of an error.
  204. var x = cast[ptr UncheckedArray[int8]](a)
  205. result = writeBuffer(f, addr(x[int(start)]), len)
  206. when defined(windows):
  207. proc writeWindows(f: File; s: string; doRaise = false) =
  208. # Don't ask why but the 'printf' family of function is the only thing
  209. # that writes utf-8 strings reliably on Windows. At least on my Win 10
  210. # machine. We also enable `setConsoleOutputCP(65001)` now by default.
  211. # But we cannot call printf directly as the string might contain \0.
  212. # So we have to loop over all the sections separated by potential \0s.
  213. var i = c_fprintf(f, "%s", s)
  214. while i < s.len:
  215. if s[i] == '\0':
  216. let w = c_fputc('\0', f)
  217. if w != 0:
  218. if doRaise: raiseEIO("cannot write string to file")
  219. break
  220. inc i
  221. else:
  222. let w = c_fprintf(f, "%s", unsafeAddr s[i])
  223. if w <= 0:
  224. if doRaise: raiseEIO("cannot write string to file")
  225. break
  226. inc i, w
  227. proc write*(f: File, s: string) {.tags: [WriteIOEffect], benign.} =
  228. when defined(windows):
  229. writeWindows(f, s, doRaise = true)
  230. else:
  231. if writeBuffer(f, cstring(s), s.len) != s.len:
  232. raiseEIO("cannot write string to file")
  233. {.pop.}
  234. when defined(nimscript):
  235. when defined(windows):
  236. const
  237. IOFBF = cint(0)
  238. IONBF = cint(4)
  239. else:
  240. # On all systems I could find, including Linux, Mac OS X, and the BSDs
  241. const
  242. IOFBF = cint(0)
  243. IONBF = cint(2)
  244. else:
  245. var
  246. IOFBF {.importc: "_IOFBF", nodecl.}: cint
  247. IONBF {.importc: "_IONBF", nodecl.}: cint
  248. const SupportIoctlInheritCtl = (defined(linux) or defined(bsd)) and
  249. not defined(nimscript)
  250. when SupportIoctlInheritCtl:
  251. var
  252. FIOCLEX {.importc, header: "<sys/ioctl.h>".}: cint
  253. FIONCLEX {.importc, header: "<sys/ioctl.h>".}: cint
  254. proc c_ioctl(fd: cint, request: cint): cint {.
  255. importc: "ioctl", header: "<sys/ioctl.h>", varargs.}
  256. elif defined(posix) and not defined(lwip) and not defined(nimscript):
  257. var
  258. F_GETFD {.importc, header: "<fcntl.h>".}: cint
  259. F_SETFD {.importc, header: "<fcntl.h>".}: cint
  260. FD_CLOEXEC {.importc, header: "<fcntl.h>".}: cint
  261. proc c_fcntl(fd: cint, cmd: cint): cint {.
  262. importc: "fcntl", header: "<fcntl.h>", varargs.}
  263. elif defined(windows):
  264. type
  265. WinDWORD = culong
  266. WinBOOL = cint
  267. const HANDLE_FLAG_INHERIT = 1.WinDWORD
  268. proc getOsfhandle(fd: cint): int {.
  269. importc: "_get_osfhandle", header: "<io.h>".}
  270. type
  271. IoHandle = distinct pointer
  272. ## Windows' HANDLE type. Defined as an untyped pointer but is **not**
  273. ## one. Named like this to avoid collision with other `system` modules.
  274. proc setHandleInformation(hObject: IoHandle, dwMask, dwFlags: WinDWORD):
  275. WinBOOL {.stdcall, dynlib: "kernel32",
  276. importc: "SetHandleInformation".}
  277. const
  278. BufSize = 4000
  279. proc close*(f: File) {.tags: [], gcsafe.} =
  280. ## Closes the file.
  281. if not f.isNil:
  282. discard c_fclose(f)
  283. proc readChar*(f: File): char {.tags: [ReadIOEffect].} =
  284. ## Reads a single character from the stream `f`. Should not be used in
  285. ## performance sensitive code.
  286. let x = c_fgetc(f)
  287. if x < 0:
  288. checkErr(f)
  289. raiseEOF()
  290. result = char(x)
  291. proc flushFile*(f: File) {.tags: [WriteIOEffect].} =
  292. ## Flushes `f`'s buffer.
  293. discard c_fflush(f)
  294. proc getFileHandle*(f: File): FileHandle =
  295. ## returns the file handle of the file `f`. This is only useful for
  296. ## platform specific programming.
  297. ## Note that on Windows this doesn't return the Windows-specific handle,
  298. ## but the C library's notion of a handle, whatever that means.
  299. ## Use `getOsFileHandle` instead.
  300. c_fileno(f)
  301. proc getOsFileHandle*(f: File): FileHandle =
  302. ## returns the OS file handle of the file `f`. This is only useful for
  303. ## platform specific programming.
  304. when defined(windows):
  305. result = FileHandle getOsfhandle(cint getFileHandle(f))
  306. else:
  307. result = c_fileno(f)
  308. when defined(nimdoc) or (defined(posix) and not defined(nimscript)) or defined(windows):
  309. proc setInheritable*(f: FileHandle, inheritable: bool): bool =
  310. ## control whether a file handle can be inherited by child processes. Returns
  311. ## `true` on success. This requires the OS file handle, which can be
  312. ## retrieved via `getOsFileHandle <#getOsFileHandle,File>`_.
  313. ##
  314. ## This procedure is not guaranteed to be available for all platforms. Test for
  315. ## availability with `declared() <system.html#declared,untyped>`.
  316. when SupportIoctlInheritCtl:
  317. result = c_ioctl(f, if inheritable: FIONCLEX else: FIOCLEX) != -1
  318. elif defined(freertos) or defined(zephyr):
  319. result = true
  320. elif defined(posix):
  321. var flags = c_fcntl(f, F_GETFD)
  322. if flags == -1:
  323. return false
  324. flags = if inheritable: flags and not FD_CLOEXEC else: flags or FD_CLOEXEC
  325. result = c_fcntl(f, F_SETFD, flags) != -1
  326. else:
  327. result = setHandleInformation(cast[IoHandle](f), HANDLE_FLAG_INHERIT,
  328. inheritable.WinDWORD) != 0
  329. proc readLine*(f: File, line: var string): bool {.tags: [ReadIOEffect],
  330. benign.} =
  331. ## reads a line of text from the file `f` into `line`. May throw an IO
  332. ## exception.
  333. ## A line of text may be delimited by `LF` or `CRLF`. The newline
  334. ## character(s) are not part of the returned string. Returns `false`
  335. ## if the end of the file has been reached, `true` otherwise. If
  336. ## `false` is returned `line` contains no new data.
  337. proc c_memchr(s: pointer, c: cint, n: csize_t): pointer {.
  338. importc: "memchr", header: "<string.h>".}
  339. when defined(windows) and not defined(useWinAnsi):
  340. proc readConsole(hConsoleInput: FileHandle, lpBuffer: pointer,
  341. nNumberOfCharsToRead: int32,
  342. lpNumberOfCharsRead: ptr int32,
  343. pInputControl: pointer): int32 {.
  344. importc: "ReadConsoleW", stdcall, dynlib: "kernel32".}
  345. proc getLastError(): int32 {.
  346. importc: "GetLastError", stdcall, dynlib: "kernel32", sideEffect.}
  347. proc formatMessageW(dwFlags: int32, lpSource: pointer,
  348. dwMessageId, dwLanguageId: int32,
  349. lpBuffer: pointer, nSize: int32,
  350. arguments: pointer): int32 {.
  351. importc: "FormatMessageW", stdcall, dynlib: "kernel32".}
  352. proc localFree(p: pointer) {.
  353. importc: "LocalFree", stdcall, dynlib: "kernel32".}
  354. proc isatty(f: File): bool =
  355. when defined(posix):
  356. proc isatty(fildes: FileHandle): cint {.
  357. importc: "isatty", header: "<unistd.h>".}
  358. else:
  359. proc isatty(fildes: FileHandle): cint {.
  360. importc: "_isatty", header: "<io.h>".}
  361. result = isatty(getFileHandle(f)) != 0'i32
  362. # this implies the file is open
  363. if f.isatty:
  364. const numberOfCharsToRead = 2048
  365. var numberOfCharsRead = 0'i32
  366. var buffer = newWideCString("", numberOfCharsToRead)
  367. if readConsole(getOsFileHandle(f), addr(buffer[0]),
  368. numberOfCharsToRead, addr(numberOfCharsRead), nil) == 0:
  369. var error = getLastError()
  370. var errorMsg: string
  371. var msgbuf: WideCString
  372. if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
  373. nil, error, 0, addr(msgbuf), 0, nil) != 0'i32:
  374. errorMsg = $msgbuf
  375. if msgbuf != nil:
  376. localFree(cast[pointer](msgbuf))
  377. raiseEIO("error: " & $error & " `" & errorMsg & "`")
  378. # input always ends with "\r\n"
  379. numberOfCharsRead -= 2
  380. # handle Ctrl+Z as EOF
  381. for i in 0..<numberOfCharsRead:
  382. if buffer[i].uint16 == 26: #Ctrl+Z
  383. close(f) #has the same effect as setting EOF
  384. if i == 0:
  385. line = ""
  386. return false
  387. numberOfCharsRead = i
  388. break
  389. buffer[numberOfCharsRead] = 0.Utf16Char
  390. when defined(nimv2):
  391. line = $toWideCString(buffer)
  392. else:
  393. line = $buffer
  394. return(true)
  395. var pos = 0
  396. # Use the currently reserved space for a first try
  397. var sp = max(line.len, 80)
  398. line.setLen(sp)
  399. while true:
  400. # memset to \L so that we can tell how far fgets wrote, even on EOF, where
  401. # fgets doesn't append an \L
  402. for i in 0..<sp: line[pos+i] = '\L'
  403. var fgetsSuccess: bool
  404. while true:
  405. # fixes #9634; this pattern may need to be abstracted as a template if reused;
  406. # likely other io procs need this for correctness.
  407. fgetsSuccess = c_fgets(addr line[pos], sp.cint, f) != nil
  408. if fgetsSuccess: break
  409. when not defined(nimscript):
  410. if errno == EINTR:
  411. errno = 0
  412. c_clearerr(f)
  413. continue
  414. checkErr(f)
  415. break
  416. let m = c_memchr(addr line[pos], '\L'.ord, cast[csize_t](sp))
  417. if m != nil:
  418. # \l found: Could be our own or the one by fgets, in any case, we're done
  419. var last = cast[ByteAddress](m) - cast[ByteAddress](addr line[0])
  420. if last > 0 and line[last-1] == '\c':
  421. line.setLen(last-1)
  422. return last > 1 or fgetsSuccess
  423. # We have to distinguish between two possible cases:
  424. # \0\l\0 => line ending in a null character.
  425. # \0\l\l => last line without newline, null was put there by fgets.
  426. elif last > 0 and line[last-1] == '\0':
  427. if last < pos + sp - 1 and line[last+1] != '\0':
  428. dec last
  429. line.setLen(last)
  430. return last > 0 or fgetsSuccess
  431. else:
  432. # fgets will have inserted a null byte at the end of the string.
  433. dec sp
  434. # No \l found: Increase buffer and read more
  435. inc pos, sp
  436. sp = 128 # read in 128 bytes at a time
  437. line.setLen(pos+sp)
  438. proc readLine*(f: File): string {.tags: [ReadIOEffect], benign.} =
  439. ## reads a line of text from the file `f`. May throw an IO exception.
  440. ## A line of text may be delimited by `LF` or `CRLF`. The newline
  441. ## character(s) are not part of the returned string.
  442. result = newStringOfCap(80)
  443. if not readLine(f, result): raiseEOF()
  444. proc write*(f: File, i: int) {.tags: [WriteIOEffect], benign.} =
  445. when sizeof(int) == 8:
  446. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  447. else:
  448. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  449. proc write*(f: File, i: BiggestInt) {.tags: [WriteIOEffect], benign.} =
  450. when sizeof(BiggestInt) == 8:
  451. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  452. else:
  453. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  454. proc write*(f: File, b: bool) {.tags: [WriteIOEffect], benign.} =
  455. if b: write(f, "true")
  456. else: write(f, "false")
  457. proc write*(f: File, r: float32) {.tags: [WriteIOEffect], benign.} =
  458. var buffer {.noinit.}: array[65, char]
  459. discard writeFloatToBuffer(buffer, r)
  460. if c_fprintf(f, "%s", buffer[0].addr) < 0: checkErr(f)
  461. proc write*(f: File, r: BiggestFloat) {.tags: [WriteIOEffect], benign.} =
  462. var buffer {.noinit.}: array[65, char]
  463. discard writeFloatToBuffer(buffer, r)
  464. if c_fprintf(f, "%s", buffer[0].addr) < 0: checkErr(f)
  465. proc write*(f: File, c: char) {.tags: [WriteIOEffect], benign.} =
  466. discard c_putc(cint(c), f)
  467. proc write*(f: File, a: varargs[string, `$`]) {.tags: [WriteIOEffect], benign.} =
  468. for x in items(a): write(f, x)
  469. proc readAllBuffer(file: File): string =
  470. # This proc is for File we want to read but don't know how many
  471. # bytes we need to read before the buffer is empty.
  472. result = ""
  473. var buffer = newString(BufSize)
  474. while true:
  475. var bytesRead = readBuffer(file, addr(buffer[0]), BufSize)
  476. if bytesRead == BufSize:
  477. result.add(buffer)
  478. else:
  479. buffer.setLen(bytesRead)
  480. result.add(buffer)
  481. break
  482. proc rawFileSize(file: File): int64 =
  483. # this does not raise an error opposed to `getFileSize`
  484. var oldPos = c_ftell(file)
  485. discard c_fseek(file, 0, 2) # seek the end of the file
  486. result = c_ftell(file)
  487. discard c_fseek(file, oldPos, 0)
  488. proc endOfFile*(f: File): bool {.tags: [], benign.} =
  489. ## Returns true if `f` is at the end.
  490. var c = c_fgetc(f)
  491. discard c_ungetc(c, f)
  492. return c < 0'i32
  493. #result = c_feof(f) != 0
  494. proc readAllFile(file: File, len: int64): string =
  495. # We acquire the filesize beforehand and hope it doesn't change.
  496. # Speeds things up.
  497. result = newString(len)
  498. let bytes = readBuffer(file, addr(result[0]), len)
  499. if endOfFile(file):
  500. if bytes < len:
  501. result.setLen(bytes)
  502. else:
  503. # We read all the bytes but did not reach the EOF
  504. # Try to read it as a buffer
  505. result.add(readAllBuffer(file))
  506. proc readAllFile(file: File): string =
  507. var len = rawFileSize(file)
  508. result = readAllFile(file, len)
  509. proc readAll*(file: File): string {.tags: [ReadIOEffect], benign.} =
  510. ## Reads all data from the stream `file`.
  511. ##
  512. ## Raises an IO exception in case of an error. It is an error if the
  513. ## current file position is not at the beginning of the file.
  514. # Separate handling needed because we need to buffer when we
  515. # don't know the overall length of the File.
  516. when declared(stdin):
  517. let len = if file != stdin: rawFileSize(file) else: -1
  518. else:
  519. let len = rawFileSize(file)
  520. if len > 0:
  521. result = readAllFile(file, len)
  522. else:
  523. result = readAllBuffer(file)
  524. proc writeLine*[Ty](f: File, x: varargs[Ty, `$`]) {.inline,
  525. tags: [WriteIOEffect], benign.} =
  526. ## writes the values `x` to `f` and then writes "\\n".
  527. ## May throw an IO exception.
  528. for i in items(x):
  529. write(f, i)
  530. write(f, "\n")
  531. # interface to the C procs:
  532. when defined(windows) and not defined(useWinAnsi):
  533. when defined(cpp):
  534. proc wfopen(filename, mode: WideCString): pointer {.
  535. importcpp: "_wfopen((const wchar_t*)#, (const wchar_t*)#)", nodecl.}
  536. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  537. importcpp: "_wfreopen((const wchar_t*)#, (const wchar_t*)#, #)", nodecl.}
  538. else:
  539. proc wfopen(filename, mode: WideCString): pointer {.
  540. importc: "_wfopen", nodecl.}
  541. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  542. importc: "_wfreopen", nodecl.}
  543. proc fopen(filename, mode: cstring): pointer =
  544. var f = newWideCString(filename)
  545. var m = newWideCString(mode)
  546. result = wfopen(f, m)
  547. proc freopen(filename, mode: cstring, stream: File): File =
  548. var f = newWideCString(filename)
  549. var m = newWideCString(mode)
  550. result = wfreopen(f, m, stream)
  551. else:
  552. proc fopen(filename, mode: cstring): pointer {.importc: "fopen", nodecl.}
  553. proc freopen(filename, mode: cstring, stream: File): File {.
  554. importc: "freopen", nodecl.}
  555. const
  556. NoInheritFlag =
  557. # Platform specific flag for creating a File without inheritance.
  558. when not defined(nimInheritHandles):
  559. when defined(windows):
  560. "N"
  561. elif defined(linux) or defined(bsd):
  562. "e"
  563. else:
  564. ""
  565. else:
  566. ""
  567. FormatOpen: array[FileMode, cstring] = [
  568. cstring("rb" & NoInheritFlag), "wb" & NoInheritFlag, "w+b" & NoInheritFlag,
  569. "r+b" & NoInheritFlag, "ab" & NoInheritFlag
  570. ]
  571. #"rt", "wt", "w+t", "r+t", "at"
  572. # we always use binary here as for Nim the OS line ending
  573. # should not be translated.
  574. when defined(posix) and not defined(nimscript):
  575. when defined(linux) and defined(amd64):
  576. type
  577. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  578. # fillers ensure correct size & offsets
  579. Stat {.importc: "struct stat",
  580. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  581. filler_1: array[24, char]
  582. st_mode: Mode ## Mode of file
  583. filler_2: array[144 - 24 - 4, char]
  584. proc modeIsDir(m: Mode): bool =
  585. ## Test for a directory.
  586. (m and 0o170000) == 0o40000
  587. else:
  588. type
  589. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  590. Stat {.importc: "struct stat",
  591. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  592. st_mode: Mode ## Mode of file
  593. proc modeIsDir(m: Mode): bool {.importc: "S_ISDIR", header: "<sys/stat.h>".}
  594. ## Test for a directory.
  595. proc c_fstat(a1: cint, a2: var Stat): cint {.
  596. importc: "fstat", header: "<sys/stat.h>".}
  597. proc open*(f: var File, filename: string,
  598. mode: FileMode = fmRead,
  599. bufSize: int = -1): bool {.tags: [], raises: [], benign.} =
  600. ## Opens a file named `filename` with given `mode`.
  601. ##
  602. ## Default mode is readonly. Returns true if the file could be opened.
  603. ## This throws no exception if the file could not be opened.
  604. ##
  605. ## The file handle associated with the resulting `File` is not inheritable.
  606. var p = fopen(filename.cstring, FormatOpen[mode])
  607. if p != nil:
  608. var f2 = cast[File](p)
  609. when defined(posix) and not defined(nimscript):
  610. # How `fopen` handles opening a directory is not specified in ISO C and
  611. # POSIX. We do not want to handle directories as regular files that can
  612. # be opened.
  613. var res {.noinit.}: Stat
  614. if c_fstat(getFileHandle(f2), res) >= 0'i32 and modeIsDir(res.st_mode):
  615. close(f2)
  616. return false
  617. when not defined(nimInheritHandles) and declared(setInheritable) and
  618. NoInheritFlag.len == 0:
  619. if not setInheritable(getOsFileHandle(f2), false):
  620. close(f2)
  621. return false
  622. result = true
  623. f = cast[File](p)
  624. if bufSize > 0 and bufSize <= high(cint).int:
  625. discard c_setvbuf(f, nil, IOFBF, cast[csize_t](bufSize))
  626. elif bufSize == 0:
  627. discard c_setvbuf(f, nil, IONBF, 0)
  628. proc reopen*(f: File, filename: string, mode: FileMode = fmRead): bool {.
  629. tags: [], benign.} =
  630. ## reopens the file `f` with given `filename` and `mode`. This
  631. ## is often used to redirect the `stdin`, `stdout` or `stderr`
  632. ## file variables.
  633. ##
  634. ## Default mode is readonly. Returns true if the file could be reopened.
  635. ##
  636. ## The file handle associated with `f` won't be inheritable.
  637. if freopen(filename.cstring, FormatOpen[mode], f) != nil:
  638. when not defined(nimInheritHandles) and declared(setInheritable) and
  639. NoInheritFlag.len == 0:
  640. if not setInheritable(getOsFileHandle(f), false):
  641. close(f)
  642. return false
  643. result = true
  644. proc open*(f: var File, filehandle: FileHandle,
  645. mode: FileMode = fmRead): bool {.tags: [], raises: [], benign.} =
  646. ## Creates a `File` from a `filehandle` with given `mode`.
  647. ##
  648. ## Default mode is readonly. Returns true if the file could be opened.
  649. ##
  650. ## The passed file handle will no longer be inheritable.
  651. when not defined(nimInheritHandles) and declared(setInheritable):
  652. let oshandle = when defined(windows): FileHandle getOsfhandle(filehandle) else: filehandle
  653. if not setInheritable(oshandle, false):
  654. return false
  655. f = c_fdopen(filehandle, FormatOpen[mode])
  656. result = f != nil
  657. proc open*(filename: string,
  658. mode: FileMode = fmRead, bufSize: int = -1): File =
  659. ## Opens a file named `filename` with given `mode`.
  660. ##
  661. ## Default mode is readonly. Raises an `IOError` if the file
  662. ## could not be opened.
  663. ##
  664. ## The file handle associated with the resulting `File` is not inheritable.
  665. if not open(result, filename, mode, bufSize):
  666. sysFatal(IOError, "cannot open: " & filename)
  667. proc setFilePos*(f: File, pos: int64, relativeTo: FileSeekPos = fspSet) {.benign.} =
  668. ## sets the position of the file pointer that is used for read/write
  669. ## operations. The file's first byte has the index zero.
  670. if c_fseek(f, pos, cint(relativeTo)) != 0:
  671. raiseEIO("cannot set file position")
  672. proc getFilePos*(f: File): int64 {.benign.} =
  673. ## retrieves the current position of the file pointer that is used to
  674. ## read from the file `f`. The file's first byte has the index zero.
  675. result = c_ftell(f)
  676. if result < 0: raiseEIO("cannot retrieve file position")
  677. proc getFileSize*(f: File): int64 {.tags: [ReadIOEffect], benign.} =
  678. ## retrieves the file size (in bytes) of `f`.
  679. let oldPos = getFilePos(f)
  680. discard c_fseek(f, 0, 2) # seek the end of the file
  681. result = getFilePos(f)
  682. setFilePos(f, oldPos)
  683. proc setStdIoUnbuffered*() {.tags: [], benign.} =
  684. ## Configures `stdin`, `stdout` and `stderr` to be unbuffered.
  685. when declared(stdout):
  686. discard c_setvbuf(stdout, nil, IONBF, 0)
  687. when declared(stderr):
  688. discard c_setvbuf(stderr, nil, IONBF, 0)
  689. when declared(stdin):
  690. discard c_setvbuf(stdin, nil, IONBF, 0)
  691. when declared(stdout):
  692. when defined(windows) and compileOption("threads"):
  693. const insideRLocksModule = false
  694. include "system/syslocks"
  695. var echoLock: SysLock
  696. initSysLock echoLock
  697. const stdOutLock = not defined(windows) and
  698. not defined(android) and
  699. not defined(nintendoswitch) and
  700. not defined(freertos) and
  701. not defined(zephyr) and
  702. hostOS != "any"
  703. proc echoBinSafe(args: openArray[string]) {.compilerproc.} =
  704. when defined(androidNDK):
  705. var s = ""
  706. for arg in args:
  707. s.add arg
  708. android_log_print(ANDROID_LOG_VERBOSE, "nim", s)
  709. else:
  710. # flockfile deadlocks some versions of Android 5.x.x
  711. when stdOutLock:
  712. proc flockfile(f: File) {.importc, nodecl.}
  713. proc funlockfile(f: File) {.importc, nodecl.}
  714. flockfile(stdout)
  715. when defined(windows) and compileOption("threads"):
  716. acquireSys echoLock
  717. for s in args:
  718. when defined(windows):
  719. writeWindows(stdout, s)
  720. else:
  721. discard c_fwrite(s.cstring, cast[csize_t](s.len), 1, stdout)
  722. const linefeed = "\n"
  723. discard c_fwrite(linefeed.cstring, linefeed.len, 1, stdout)
  724. discard c_fflush(stdout)
  725. when stdOutLock:
  726. funlockfile(stdout)
  727. when defined(windows) and compileOption("threads"):
  728. releaseSys echoLock
  729. when defined(windows) and not defined(nimscript) and not defined(js):
  730. # work-around C's sucking abstraction:
  731. # BUGFIX: stdin and stdout should be binary files!
  732. proc c_setmode(handle, mode: cint) {.
  733. importc: when defined(bcc): "setmode" else: "_setmode",
  734. header: "<io.h>".}
  735. var
  736. O_BINARY {.importc: "_O_BINARY", header: "<fcntl.h>".}: cint
  737. # we use binary mode on Windows:
  738. c_setmode(c_fileno(stdin), O_BINARY)
  739. c_setmode(c_fileno(stdout), O_BINARY)
  740. c_setmode(c_fileno(stderr), O_BINARY)
  741. when defined(windows) and appType == "console" and
  742. not defined(nimDontSetUtf8CodePage) and not defined(nimscript):
  743. proc setConsoleOutputCP(codepage: cuint): int32 {.stdcall, dynlib: "kernel32",
  744. importc: "SetConsoleOutputCP".}
  745. proc setConsoleCP(wCodePageID: cuint): int32 {.stdcall, dynlib: "kernel32",
  746. importc: "SetConsoleCP".}
  747. const Utf8codepage = 65001
  748. discard setConsoleOutputCP(Utf8codepage)
  749. discard setConsoleCP(Utf8codepage)
  750. proc readFile*(filename: string): string {.tags: [ReadIOEffect], benign.} =
  751. ## Opens a file named `filename` for reading, calls `readAll
  752. ## <#readAll,File>`_ and closes the file afterwards. Returns the string.
  753. ## Raises an IO exception in case of an error. If you need to call
  754. ## this inside a compile time macro you can use `staticRead
  755. ## <system.html#staticRead,string>`_.
  756. var f: File = nil
  757. if open(f, filename):
  758. try:
  759. result = readAll(f)
  760. finally:
  761. close(f)
  762. else:
  763. sysFatal(IOError, "cannot open: " & filename)
  764. proc writeFile*(filename, content: string) {.tags: [WriteIOEffect], benign.} =
  765. ## Opens a file named `filename` for writing. Then writes the
  766. ## `content` completely to the file and closes the file afterwards.
  767. ## Raises an IO exception in case of an error.
  768. var f: File = nil
  769. if open(f, filename, fmWrite):
  770. try:
  771. f.write(content)
  772. finally:
  773. close(f)
  774. else:
  775. sysFatal(IOError, "cannot open: " & filename)
  776. proc writeFile*(filename: string, content: openArray[byte]) {.since: (1, 1).} =
  777. ## Opens a file named `filename` for writing. Then writes the
  778. ## `content` completely to the file and closes the file afterwards.
  779. ## Raises an IO exception in case of an error.
  780. var f: File = nil
  781. if open(f, filename, fmWrite):
  782. try:
  783. f.writeBuffer(unsafeAddr content[0], content.len)
  784. finally:
  785. close(f)
  786. else:
  787. raise newException(IOError, "cannot open: " & filename)
  788. proc readLines*(filename: string, n: Natural): seq[string] =
  789. ## read `n` lines from the file named `filename`. Raises an IO exception
  790. ## in case of an error. Raises EOF if file does not contain at least `n` lines.
  791. ## Available at compile time. A line of text may be delimited by `LF` or `CRLF`.
  792. ## The newline character(s) are not part of the returned strings.
  793. var f: File = nil
  794. if open(f, filename):
  795. try:
  796. result = newSeq[string](n)
  797. for i in 0 .. n - 1:
  798. if not readLine(f, result[i]):
  799. raiseEOF()
  800. finally:
  801. close(f)
  802. else:
  803. sysFatal(IOError, "cannot open: " & filename)
  804. template readLines*(filename: string): seq[string] {.deprecated: "use readLines with two arguments".} =
  805. readLines(filename, 1)
  806. iterator lines*(filename: string): string {.tags: [ReadIOEffect].} =
  807. ## Iterates over any line in the file named `filename`.
  808. ##
  809. ## If the file does not exist `IOError` is raised. The trailing newline
  810. ## character(s) are removed from the iterated lines. Example:
  811. ##
  812. runnableExamples:
  813. import std/strutils
  814. proc transformLetters(filename: string) =
  815. var buffer = ""
  816. for line in filename.lines:
  817. buffer.add(line.replace("a", "0") & '\n')
  818. writeFile(filename, buffer)
  819. var f = open(filename, bufSize=8000)
  820. try:
  821. var res = newStringOfCap(80)
  822. while f.readLine(res): yield res
  823. finally:
  824. close(f)
  825. iterator lines*(f: File): string {.tags: [ReadIOEffect].} =
  826. ## Iterate over any line in the file `f`.
  827. ##
  828. ## The trailing newline character(s) are removed from the iterated lines.
  829. ##
  830. runnableExamples:
  831. proc countZeros(filename: File): tuple[lines, zeros: int] =
  832. for line in filename.lines:
  833. for letter in line:
  834. if letter == '0':
  835. result.zeros += 1
  836. result.lines += 1
  837. var res = newStringOfCap(80)
  838. while f.readLine(res): yield res