io.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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): csize_t {.
  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(cast[cstring](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. elif last > 0 and line[last-1] == '\0':
  424. # We have to distinguish among three possible cases:
  425. # \0\l\0 => line ending in a null character.
  426. # \0\l\l => last line without newline, null was put there by fgets.
  427. # \0\l => last line without newline, null was put there by fgets.
  428. if last >= pos + sp - 1 or line[last+1] != '\0': # bug #21273
  429. dec last
  430. line.setLen(last)
  431. return last > 0 or fgetsSuccess
  432. else:
  433. # fgets will have inserted a null byte at the end of the string.
  434. dec sp
  435. # No \l found: Increase buffer and read more
  436. inc pos, sp
  437. sp = 128 # read in 128 bytes at a time
  438. line.setLen(pos+sp)
  439. proc readLine*(f: File): string {.tags: [ReadIOEffect], benign.} =
  440. ## reads a line of text from the file `f`. May throw an IO exception.
  441. ## A line of text may be delimited by `LF` or `CRLF`. The newline
  442. ## character(s) are not part of the returned string.
  443. result = newStringOfCap(80)
  444. if not readLine(f, result): raiseEOF()
  445. proc write*(f: File, i: int) {.tags: [WriteIOEffect], benign.} =
  446. when sizeof(int) == 8:
  447. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  448. else:
  449. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  450. proc write*(f: File, i: BiggestInt) {.tags: [WriteIOEffect], benign.} =
  451. when sizeof(BiggestInt) == 8:
  452. if c_fprintf(f, "%lld", i) < 0: checkErr(f)
  453. else:
  454. if c_fprintf(f, "%ld", i) < 0: checkErr(f)
  455. proc write*(f: File, b: bool) {.tags: [WriteIOEffect], benign.} =
  456. if b: write(f, "true")
  457. else: write(f, "false")
  458. proc write*(f: File, r: float32) {.tags: [WriteIOEffect], benign.} =
  459. var buffer {.noinit.}: array[65, char]
  460. discard writeFloatToBuffer(buffer, r)
  461. if c_fprintf(f, "%s", buffer[0].addr) < 0: checkErr(f)
  462. proc write*(f: File, r: BiggestFloat) {.tags: [WriteIOEffect], benign.} =
  463. var buffer {.noinit.}: array[65, char]
  464. discard writeFloatToBuffer(buffer, r)
  465. if c_fprintf(f, "%s", buffer[0].addr) < 0: checkErr(f)
  466. proc write*(f: File, c: char) {.tags: [WriteIOEffect], benign.} =
  467. discard c_putc(cint(c), f)
  468. proc write*(f: File, a: varargs[string, `$`]) {.tags: [WriteIOEffect], benign.} =
  469. for x in items(a): write(f, x)
  470. proc readAllBuffer(file: File): string =
  471. # This proc is for File we want to read but don't know how many
  472. # bytes we need to read before the buffer is empty.
  473. result = ""
  474. var buffer = newString(BufSize)
  475. while true:
  476. var bytesRead = readBuffer(file, addr(buffer[0]), BufSize)
  477. if bytesRead == BufSize:
  478. result.add(buffer)
  479. else:
  480. buffer.setLen(bytesRead)
  481. result.add(buffer)
  482. break
  483. proc rawFileSize(file: File): int64 =
  484. # this does not raise an error opposed to `getFileSize`
  485. var oldPos = c_ftell(file)
  486. discard c_fseek(file, 0, 2) # seek the end of the file
  487. result = c_ftell(file)
  488. discard c_fseek(file, oldPos, 0)
  489. proc endOfFile*(f: File): bool {.tags: [], benign.} =
  490. ## Returns true if `f` is at the end.
  491. var c = c_fgetc(f)
  492. discard c_ungetc(c, f)
  493. return c < 0'i32
  494. #result = c_feof(f) != 0
  495. proc readAllFile(file: File, len: int64): string =
  496. # We acquire the filesize beforehand and hope it doesn't change.
  497. # Speeds things up.
  498. result = newString(len)
  499. let bytes = readBuffer(file, addr(result[0]), len)
  500. if endOfFile(file):
  501. if bytes < len:
  502. result.setLen(bytes)
  503. else:
  504. # We read all the bytes but did not reach the EOF
  505. # Try to read it as a buffer
  506. result.add(readAllBuffer(file))
  507. proc readAllFile(file: File): string =
  508. var len = rawFileSize(file)
  509. result = readAllFile(file, len)
  510. proc readAll*(file: File): string {.tags: [ReadIOEffect], benign.} =
  511. ## Reads all data from the stream `file`.
  512. ##
  513. ## Raises an IO exception in case of an error. It is an error if the
  514. ## current file position is not at the beginning of the file.
  515. # Separate handling needed because we need to buffer when we
  516. # don't know the overall length of the File.
  517. when declared(stdin):
  518. let len = if file != stdin: rawFileSize(file) else: -1
  519. else:
  520. let len = rawFileSize(file)
  521. if len > 0:
  522. result = readAllFile(file, len)
  523. else:
  524. result = readAllBuffer(file)
  525. proc writeLine*[Ty](f: File, x: varargs[Ty, `$`]) {.inline,
  526. tags: [WriteIOEffect], benign.} =
  527. ## writes the values `x` to `f` and then writes "\\n".
  528. ## May throw an IO exception.
  529. for i in items(x):
  530. write(f, i)
  531. write(f, "\n")
  532. # interface to the C procs:
  533. when defined(windows) and not defined(useWinAnsi):
  534. when defined(cpp):
  535. proc wfopen(filename, mode: WideCString): pointer {.
  536. importcpp: "_wfopen((const wchar_t*)#, (const wchar_t*)#)", nodecl.}
  537. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  538. importcpp: "_wfreopen((const wchar_t*)#, (const wchar_t*)#, #)", nodecl.}
  539. else:
  540. proc wfopen(filename, mode: WideCString): pointer {.
  541. importc: "_wfopen", nodecl.}
  542. proc wfreopen(filename, mode: WideCString, stream: File): File {.
  543. importc: "_wfreopen", nodecl.}
  544. proc fopen(filename, mode: cstring): pointer =
  545. var f = newWideCString(filename)
  546. var m = newWideCString(mode)
  547. result = wfopen(f, m)
  548. proc freopen(filename, mode: cstring, stream: File): File =
  549. var f = newWideCString(filename)
  550. var m = newWideCString(mode)
  551. result = wfreopen(f, m, stream)
  552. else:
  553. proc fopen(filename, mode: cstring): pointer {.importc: "fopen", nodecl.}
  554. proc freopen(filename, mode: cstring, stream: File): File {.
  555. importc: "freopen", nodecl.}
  556. const
  557. NoInheritFlag =
  558. # Platform specific flag for creating a File without inheritance.
  559. when not defined(nimInheritHandles):
  560. when defined(windows):
  561. "N"
  562. elif defined(linux) or defined(bsd):
  563. "e"
  564. else:
  565. ""
  566. else:
  567. ""
  568. FormatOpen: array[FileMode, cstring] = [
  569. cstring("rb" & NoInheritFlag), "wb" & NoInheritFlag, "w+b" & NoInheritFlag,
  570. "r+b" & NoInheritFlag, "ab" & NoInheritFlag
  571. ]
  572. #"rt", "wt", "w+t", "r+t", "at"
  573. # we always use binary here as for Nim the OS line ending
  574. # should not be translated.
  575. when defined(posix) and not defined(nimscript):
  576. when defined(linux) and defined(amd64):
  577. type
  578. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  579. # fillers ensure correct size & offsets
  580. Stat {.importc: "struct stat",
  581. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  582. filler_1: array[24, char]
  583. st_mode: Mode ## Mode of file
  584. filler_2: array[144 - 24 - 4, char]
  585. proc modeIsDir(m: Mode): bool =
  586. ## Test for a directory.
  587. (m and 0o170000) == 0o40000
  588. else:
  589. type
  590. Mode {.importc: "mode_t", header: "<sys/types.h>".} = cint
  591. Stat {.importc: "struct stat",
  592. header: "<sys/stat.h>", final, pure.} = object ## struct stat
  593. st_mode: Mode ## Mode of file
  594. proc modeIsDir(m: Mode): bool {.importc: "S_ISDIR", header: "<sys/stat.h>".}
  595. ## Test for a directory.
  596. proc c_fstat(a1: cint, a2: var Stat): cint {.
  597. importc: "fstat", header: "<sys/stat.h>".}
  598. proc open*(f: var File, filename: string,
  599. mode: FileMode = fmRead,
  600. bufSize: int = -1): bool {.tags: [], raises: [], benign.} =
  601. ## Opens a file named `filename` with given `mode`.
  602. ##
  603. ## Default mode is readonly. Returns true if the file could be opened.
  604. ## This throws no exception if the file could not be opened.
  605. ##
  606. ## The file handle associated with the resulting `File` is not inheritable.
  607. var p = fopen(filename.cstring, FormatOpen[mode])
  608. if p != nil:
  609. var f2 = cast[File](p)
  610. when defined(posix) and not defined(nimscript):
  611. # How `fopen` handles opening a directory is not specified in ISO C and
  612. # POSIX. We do not want to handle directories as regular files that can
  613. # be opened.
  614. var res {.noinit.}: Stat
  615. if c_fstat(getFileHandle(f2), res) >= 0'i32 and modeIsDir(res.st_mode):
  616. close(f2)
  617. return false
  618. when not defined(nimInheritHandles) and declared(setInheritable) and
  619. NoInheritFlag.len == 0:
  620. if not setInheritable(getOsFileHandle(f2), false):
  621. close(f2)
  622. return false
  623. result = true
  624. f = cast[File](p)
  625. if bufSize > 0 and bufSize <= high(cint).int:
  626. discard c_setvbuf(f, nil, IOFBF, cast[csize_t](bufSize))
  627. elif bufSize == 0:
  628. discard c_setvbuf(f, nil, IONBF, 0)
  629. proc reopen*(f: File, filename: string, mode: FileMode = fmRead): bool {.
  630. tags: [], benign.} =
  631. ## reopens the file `f` with given `filename` and `mode`. This
  632. ## is often used to redirect the `stdin`, `stdout` or `stderr`
  633. ## file variables.
  634. ##
  635. ## Default mode is readonly. Returns true if the file could be reopened.
  636. ##
  637. ## The file handle associated with `f` won't be inheritable.
  638. if freopen(filename.cstring, FormatOpen[mode], f) != nil:
  639. when not defined(nimInheritHandles) and declared(setInheritable) and
  640. NoInheritFlag.len == 0:
  641. if not setInheritable(getOsFileHandle(f), false):
  642. close(f)
  643. return false
  644. result = true
  645. proc open*(f: var File, filehandle: FileHandle,
  646. mode: FileMode = fmRead): bool {.tags: [], raises: [], benign.} =
  647. ## Creates a `File` from a `filehandle` with given `mode`.
  648. ##
  649. ## Default mode is readonly. Returns true if the file could be opened.
  650. ##
  651. ## The passed file handle will no longer be inheritable.
  652. when not defined(nimInheritHandles) and declared(setInheritable):
  653. let oshandle = when defined(windows): FileHandle getOsfhandle(filehandle) else: filehandle
  654. if not setInheritable(oshandle, false):
  655. return false
  656. f = c_fdopen(filehandle, FormatOpen[mode])
  657. result = f != nil
  658. proc open*(filename: string,
  659. mode: FileMode = fmRead, bufSize: int = -1): File =
  660. ## Opens a file named `filename` with given `mode`.
  661. ##
  662. ## Default mode is readonly. Raises an `IOError` if the file
  663. ## could not be opened.
  664. ##
  665. ## The file handle associated with the resulting `File` is not inheritable.
  666. if not open(result, filename, mode, bufSize):
  667. sysFatal(IOError, "cannot open: " & filename)
  668. proc setFilePos*(f: File, pos: int64, relativeTo: FileSeekPos = fspSet) {.benign.} =
  669. ## sets the position of the file pointer that is used for read/write
  670. ## operations. The file's first byte has the index zero.
  671. if c_fseek(f, pos, cint(relativeTo)) != 0:
  672. raiseEIO("cannot set file position")
  673. proc getFilePos*(f: File): int64 {.benign.} =
  674. ## retrieves the current position of the file pointer that is used to
  675. ## read from the file `f`. The file's first byte has the index zero.
  676. result = c_ftell(f)
  677. if result < 0: raiseEIO("cannot retrieve file position")
  678. proc getFileSize*(f: File): int64 {.tags: [ReadIOEffect], benign.} =
  679. ## retrieves the file size (in bytes) of `f`.
  680. let oldPos = getFilePos(f)
  681. discard c_fseek(f, 0, 2) # seek the end of the file
  682. result = getFilePos(f)
  683. setFilePos(f, oldPos)
  684. proc setStdIoUnbuffered*() {.tags: [], benign.} =
  685. ## Configures `stdin`, `stdout` and `stderr` to be unbuffered.
  686. when declared(stdout):
  687. discard c_setvbuf(stdout, nil, IONBF, 0)
  688. when declared(stderr):
  689. discard c_setvbuf(stderr, nil, IONBF, 0)
  690. when declared(stdin):
  691. discard c_setvbuf(stdin, nil, IONBF, 0)
  692. when declared(stdout):
  693. when defined(windows) and compileOption("threads"):
  694. const insideRLocksModule = false
  695. include "system/syslocks"
  696. var echoLock: SysLock
  697. initSysLock echoLock
  698. const stdOutLock = not defined(windows) and
  699. not defined(android) and
  700. not defined(nintendoswitch) and
  701. not defined(freertos) and
  702. not defined(zephyr) and
  703. hostOS != "any"
  704. proc echoBinSafe(args: openArray[string]) {.compilerproc.} =
  705. when defined(androidNDK):
  706. var s = ""
  707. for arg in args:
  708. s.add arg
  709. android_log_print(ANDROID_LOG_VERBOSE, "nim", s)
  710. else:
  711. # flockfile deadlocks some versions of Android 5.x.x
  712. when stdOutLock:
  713. proc flockfile(f: File) {.importc, nodecl.}
  714. proc funlockfile(f: File) {.importc, nodecl.}
  715. flockfile(stdout)
  716. when defined(windows) and compileOption("threads"):
  717. acquireSys echoLock
  718. for s in args:
  719. when defined(windows):
  720. writeWindows(stdout, s)
  721. else:
  722. discard c_fwrite(s.cstring, cast[csize_t](s.len), 1, stdout)
  723. const linefeed = "\n"
  724. discard c_fwrite(linefeed.cstring, linefeed.len, 1, stdout)
  725. discard c_fflush(stdout)
  726. when stdOutLock:
  727. funlockfile(stdout)
  728. when defined(windows) and compileOption("threads"):
  729. releaseSys echoLock
  730. when defined(windows) and not defined(nimscript) and not defined(js):
  731. # work-around C's sucking abstraction:
  732. # BUGFIX: stdin and stdout should be binary files!
  733. proc c_setmode(handle, mode: cint) {.
  734. importc: when defined(bcc): "setmode" else: "_setmode",
  735. header: "<io.h>".}
  736. var
  737. O_BINARY {.importc: "_O_BINARY", header: "<fcntl.h>".}: cint
  738. # we use binary mode on Windows:
  739. c_setmode(c_fileno(stdin), O_BINARY)
  740. c_setmode(c_fileno(stdout), O_BINARY)
  741. c_setmode(c_fileno(stderr), O_BINARY)
  742. when defined(windows) and appType == "console" and
  743. not defined(nimDontSetUtf8CodePage) and not defined(nimscript):
  744. proc setConsoleOutputCP(codepage: cuint): int32 {.stdcall, dynlib: "kernel32",
  745. importc: "SetConsoleOutputCP".}
  746. proc setConsoleCP(wCodePageID: cuint): int32 {.stdcall, dynlib: "kernel32",
  747. importc: "SetConsoleCP".}
  748. const Utf8codepage = 65001
  749. discard setConsoleOutputCP(Utf8codepage)
  750. discard setConsoleCP(Utf8codepage)
  751. proc readFile*(filename: string): string {.tags: [ReadIOEffect], benign.} =
  752. ## Opens a file named `filename` for reading, calls `readAll
  753. ## <#readAll,File>`_ and closes the file afterwards. Returns the string.
  754. ## Raises an IO exception in case of an error. If you need to call
  755. ## this inside a compile time macro you can use `staticRead
  756. ## <system.html#staticRead,string>`_.
  757. var f: File = nil
  758. if open(f, filename):
  759. try:
  760. result = readAll(f)
  761. finally:
  762. close(f)
  763. else:
  764. sysFatal(IOError, "cannot open: " & filename)
  765. proc writeFile*(filename, content: string) {.tags: [WriteIOEffect], benign.} =
  766. ## Opens a file named `filename` for writing. Then writes the
  767. ## `content` completely to the file and closes the file afterwards.
  768. ## Raises an IO exception in case of an error.
  769. var f: File = nil
  770. if open(f, filename, fmWrite):
  771. try:
  772. f.write(content)
  773. finally:
  774. close(f)
  775. else:
  776. sysFatal(IOError, "cannot open: " & filename)
  777. proc writeFile*(filename: string, content: openArray[byte]) {.since: (1, 1).} =
  778. ## Opens a file named `filename` for writing. Then writes the
  779. ## `content` completely to the file and closes the file afterwards.
  780. ## Raises an IO exception in case of an error.
  781. var f: File = nil
  782. if open(f, filename, fmWrite):
  783. try:
  784. f.writeBuffer(unsafeAddr content[0], content.len)
  785. finally:
  786. close(f)
  787. else:
  788. raise newException(IOError, "cannot open: " & filename)
  789. proc readLines*(filename: string, n: Natural): seq[string] =
  790. ## read `n` lines from the file named `filename`. Raises an IO exception
  791. ## in case of an error. Raises EOF if file does not contain at least `n` lines.
  792. ## Available at compile time. A line of text may be delimited by `LF` or `CRLF`.
  793. ## The newline character(s) are not part of the returned strings.
  794. var f: File = nil
  795. if open(f, filename):
  796. try:
  797. result = newSeq[string](n)
  798. for i in 0 .. n - 1:
  799. if not readLine(f, result[i]):
  800. raiseEOF()
  801. finally:
  802. close(f)
  803. else:
  804. sysFatal(IOError, "cannot open: " & filename)
  805. template readLines*(filename: string): seq[string] {.deprecated: "use readLines with two arguments".} =
  806. readLines(filename, 1)
  807. iterator lines*(filename: string): string {.tags: [ReadIOEffect].} =
  808. ## Iterates over any line in the file named `filename`.
  809. ##
  810. ## If the file does not exist `IOError` is raised. The trailing newline
  811. ## character(s) are removed from the iterated lines. Example:
  812. ##
  813. runnableExamples:
  814. import std/strutils
  815. proc transformLetters(filename: string) =
  816. var buffer = ""
  817. for line in filename.lines:
  818. buffer.add(line.replace("a", "0") & '\n')
  819. writeFile(filename, buffer)
  820. var f = open(filename, bufSize=8000)
  821. try:
  822. var res = newStringOfCap(80)
  823. while f.readLine(res): yield res
  824. finally:
  825. close(f)
  826. iterator lines*(f: File): string {.tags: [ReadIOEffect].} =
  827. ## Iterate over any line in the file `f`.
  828. ##
  829. ## The trailing newline character(s) are removed from the iterated lines.
  830. ##
  831. runnableExamples:
  832. proc countZeros(filename: File): tuple[lines, zeros: int] =
  833. for line in filename.lines:
  834. for letter in line:
  835. if letter == '0':
  836. result.zeros += 1
  837. result.lines += 1
  838. var res = newStringOfCap(80)
  839. while f.readLine(res): yield res