// // FileWriter.swift // PrySDR // // Created by Jacky Jack on 21/01/2025. // import Foundation enum FileWriterError: Error { case noFile case writeError case createError } class FileWriter { var filepath: String? let filemgr = FileManager.default var fileHandle: FileHandle? init() { } func openForRead(filename: String) throws { let dir = getCurrentExecutableDir() self.filepath = dir+"/"+filename print(dir+"/"+filename) if !filemgr.fileExists(atPath: filename) { print("Cant find file \(filename)") throw FileWriterError.noFile } fileHandle = FileHandle(forReadingAtPath: dir+"/"+filename) if (fileHandle == nil) { print("FileHandler failed") } } func createForWrite(filename: String) throws { let dir = getCurrentExecutableDir() self.filepath = dir+"/"+filename if !filemgr.fileExists(atPath: filename) { filemgr.createFile(atPath: dir+"/"+filename, contents: nil) } fileHandle = FileHandle(forUpdatingAtPath: dir+"/"+filename) if (fileHandle == nil) { print("FileHandler failed") throw FileWriterError.createError } } func deleteForWrite(filename: String) throws { let dir = getCurrentExecutableDir() self.filepath = dir+"/"+filename if filemgr.fileExists(atPath: filename) { do { try filemgr.removeItem(atPath: filename) filemgr.createFile(atPath: dir+"/"+filename, contents: nil) } catch { print("couldnt delete file to write: \(error)") } } fileHandle = FileHandle(forWritingAtPath: dir+"/"+filename) if (fileHandle == nil) { print("FileHandler failed") throw FileWriterError.createError } } func writeAll(_ arr: [Float32]) throws { var byteArray = [UInt8](repeating: 0, count: 0) var b1:Data = Data() byteArray.append(contentsOf: [0x11,0x22,0x33,0x44]) arr.withUnsafeBytes { byteArray.append(contentsOf: $0) } for i in 0...arr.count { b1.append(contentsOf: [byteArray[i*4+0],byteArray[i*4+1],byteArray[i*4+2],byteArray[i*4+3]]) } do { print("try to write \(b1.count) bytes") try fileHandle?.write(contentsOf: b1) } catch { print("Cant write to file \(self.filepath) : \(error)") throw FileWriterError.writeError } } func writeAll(_ arr: [Int8]) throws { var byteArray = [UInt8](repeating: 0, count: 0) var b1:Data = Data() arr.withUnsafeBytes { byteArray.append(contentsOf: $0) } for i in 0..