syncio.nim 35 KB

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