From 01a10abe29ac368b457555d28ba130564860532b Mon Sep 17 00:00:00 2001 From: Andy Liu Date: Sat, 4 Nov 2023 15:21:23 +0800 Subject: [PATCH] Modify File operation API Signed-off-by: Andy Liu --- .../Pong/Sources/Pong/Game.swift | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/Examples/SwiftIOPlayground/11MoreProjects/Pong/Sources/Pong/Game.swift b/Examples/SwiftIOPlayground/11MoreProjects/Pong/Sources/Pong/Game.swift index 253100d..2056941 100644 --- a/Examples/SwiftIOPlayground/11MoreProjects/Pong/Sources/Pong/Game.swift +++ b/Examples/SwiftIOPlayground/11MoreProjects/Pong/Sources/Pong/Game.swift @@ -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