// // 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 FileReaderError.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 { //convert float to data let databuf = arr.withUnsafeBytes { Data($0) } do { print("try to write \(databuf.count) bytes") try fileHandle?.write(contentsOf: databuf) } catch { print("Cant write to file \(self.filepath) : \(error)") throw FileWriterError.writeError } } func close() { fileHandle?.closeFile() } }