Skip to content

Commit 9079517

Browse files
twetzel59Araq
authored andcommitted
Resolves #5588: adds openFileStream proc that throws on failure (#7282)
1 parent 4164ec4 commit 9079517

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/pure/streams.nim

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,9 +447,19 @@ when not defined(js):
447447
## creates a new stream from the file named `filename` with the mode `mode`.
448448
## If the file cannot be opened, nil is returned. See the `system
449449
## <system.html>`_ module for a list of available FileMode enums.
450+
## **This function returns nil in case of failure. To prevent unexpected
451+
## behavior and ensure proper error handling, use openFileStream instead.**
450452
var f: File
451453
if open(f, filename, mode, bufSize): result = newFileStream(f)
452454

455+
proc openFileStream*(filename: string, mode: FileMode = fmRead, bufSize: int = -1): FileStream =
456+
## creates a new stream from the file named `filename` with the mode `mode`.
457+
## If the file cannot be opened, an IO exception is raised.
458+
var f: File
459+
if open(f, filename, mode, bufSize):
460+
return newFileStream(f)
461+
else:
462+
raise newEIO("cannot open file")
453463

454464
when true:
455465
discard

tests/stdlib/tstreams3.nim

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
discard """
2+
file: "tstreams3.nim"
3+
output: "threw exception"
4+
"""
5+
import streams
6+
7+
try:
8+
var fs = openFileStream("shouldneverexist.txt")
9+
except IoError:
10+
echo "threw exception"

0 commit comments

Comments
 (0)