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