-
Notifications
You must be signed in to change notification settings - Fork 2
FileStream
Evan Swick edited this page Feb 18, 2016
·
3 revisions
FileStream
is a stream for interfacing with files on the filesystem. It is a convenient wrapper over IOStream
to automatically set up a file descriptor.
The designated initializer for FileStream
:
init(path: String, mode: FileMode = .OpenOrCreate, access: FileAccess = .ReadWrite, creationFlags: FileFlags = FileFlags(rawValue: 0o644)) throws
creationFlags
is only used for the .CreateNew
, .Create
, and .OpenOrCreate
file modes.
The FileMode
enumeration is used to specify how the operating system should open a file.
-
.Append
- Opens the file if it exists and seeks to the end of the file, or creates a new file.
- Only compatible with
.Read
access mode
-
.Create
- Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
.Create
is equivalent to requesting that if the file does not exist, use.CreateNew
; otherwise, use.Truncate
. - Requires
.Write
or.ReadWrite
access mode
- Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
-
.CreateNew
- Specifies that the operating system should create a new file.
- If the file already exists, an
FileStreamError.FileExists
is thrown.
-
.Open
- Specifies that the operating system should open an existing file.
-
.OpenOrCreate
- Specifies that the operating system should open a file if it exists; otherwise, a new file should be created.
-
.Truncate
- Specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes.
- Requires the
.Write
or.ReadWrite
access mode
// open a file, create it if it doesn't exist, and write to it
do {
var fstream = try FileStream(path: "/Users/eswick/Desktop/testfile")
} catch let e as FileStreamError.FileNotFound {
print("File not found!")
} catch {
print("An error occurred while opening the file.")
}
try fstream.write("Hello, world!")
// create a new file, truncating it if it already exists
var flags = FileFlags(rawValue: 0o775)
var fstream = try FileStream(path: "/Users/eswick/Desktop/newfile", mode: .Create, creationFlags: flags)
// ...
// open device and read from it
var urandom = try FileStream(path: "/dev/urandom", mode: .Open)
print(try urandom.read(15))
Copyright © 2016 Evan Swick