Hi, how can I read a text from a file on MacOS?
# kotlin-native
g
Hi, how can I read a text from a file on MacOS?
Currently I have this
Copy code
actual suspend fun MPFile<Any>.toDomainModel(): HistoryFile {
    val selectedFile = (platformFile as NSURL)
    var fileContents: String = ""
    
    memScoped {
        val file = fopen(selectedFile.path, "r")
        if (file != null) {
            val bufferSize = 1024
            val buffer = ByteArray(bufferSize)

            while (true) {
                val bytesRead = fread(buffer.refTo(0), 1.convert(), bufferSize.convert(), file)
                if (bytesRead <= 0u) break
                val contentChunk = buffer.copyOfRange(0, bytesRead.toInt())
                fileContents += contentChunk.decodeToString()
            }

            fclose(file)
        } else {
            println("Failed to open the file.")
        }
    }
    return HistoryFile(path, fileContents)
}
But it is very slow. On some websites I found this Swift code
Copy code
let file = "/Users/user/Documents/text.txt"
    let path=URL(fileURLWithPath: file)
    let text=try? String(contentsOf: path)
How can I convert it to Kotlin?
m
Most likely the slow thing is to allocate a new string every iteration. Use Okio filesystem, you'll have KMP support and something that is well tested
Something like this:
Copy code
FileSystem.SYSTEM.openReadOnly("path/to/file.txt".toPath()).source().buffer().readUtf8()
🚀 1
g
📌