Skip to content

Commit

Permalink
Modify File operation API
Browse files Browse the repository at this point in the history
Signed-off-by: Andy Liu <andy@madmachine.io>
  • Loading branch information
andy0808 committed Nov 4, 2023
1 parent b1d6eb6 commit 01a10ab
Showing 1 changed file with 18 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -177,15 +177,26 @@ struct PongGame {
func readSoundData(from path: String) -> [UInt8] {
let headerSize = 0x2C

let file = FileDescriptor.open(path)
defer { file.close() }
let _file = try? FileDescriptor.open(path)
guard let file = _file else {
print("Read sound data \(path) failed!")
return []
}

var buffer = [UInt8]()

file.seek(offset: 0, from: FileDescriptor.SeekOrigin.end)
let size = file.tell() - headerSize
do {
try file.seek(offset: 0, from: FileDescriptor.SeekOrigin.end)
let size = try file.tell() - headerSize

var buffer = [UInt8](repeating: 0, count: size)
buffer.withUnsafeMutableBytes { rawBuffer in
_ = file.read(fromAbsoluteOffest: headerSize, into: rawBuffer, count: size)
buffer = [UInt8](repeating: 0, count: size)
try buffer.withUnsafeMutableBytes { rawBuffer in
_ = try file.read(fromAbsoluteOffest: headerSize, into: rawBuffer, count: size)
}
try file.close()
} catch {
print("File \(path) handle error: \(error)")
return []
}

return buffer
Expand Down

0 comments on commit 01a10ab

Please sign in to comment.