FileDescriptor
The FileDescriptor struct is used to perform low-level file operations.
struct FileDescriptor
Example: Open and read an ASCII file
import SwiftIO
// Open the file located in "/subDir/hello.txt"
if let file = try? FileDescriptor.open("/SD:/subDir/hello.txt") {
//Initialize a buffer to store the reading bytes.
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: 10, alignment: 4)
do {
// Read bytes into the buffer
try file.read(into: buffer)
// Print the reding bytes.
for i in 0..<buffer.count {
print(buffer[i])
}
} catch {
print("Unexpected error: \(error).")
}
}
while true {
sleep(ms: 1000)
}
Opening a File
static func open(String, FileDescriptor.AccessMode, options: FileDescriptor.OpenOptions
) throws Open or creates, if does not exist, file.
struct AccessMode
The desired read and write access for a newly opened file.
struct OpenOptions
Options that specify behavior for a newly-opened file.
Reading from a file
read(into:count:)-1e6cm
read(into:count:)-3x3lj
read(fromAbsoluteOffest:into:count:)-6abp2
read(fromAbsoluteOffest:into:count:)-k2ts
Writing to a file
func write(String
) throws Writes the contents of a string at the current file offset.
write(_:count:)-8l97n
write(_:count:)-2p42a
write(toAbsoluteOffset:_:count:)-42r4g
write(toAbsoluteOffset:_:count:)-7r2v8
Closing a File
func close(
) throws Flushes the associated stream and closes the file.
Changing a File’s Offset
func seek(offset: Int, from: SeekOrigin
) throws Repositions the offset for the given file descriptor.
struct SeekOrigin
Options for specifying what a file descriptor’s offset is relative to.