1
0
Fork 0
happy-cat/src/nativeMain/kotlin/fi/schro/util/FileUtil.kt

42 lines
1.2 KiB
Kotlin

/*
* Copyright (c) 2022 Florian Schrofner
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package fi.schro.util
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.toKString
import platform.posix.fclose
import platform.posix.fgets
import platform.posix.fopen
class FileUtilImpl: FileUtil {
override fun readAllText(filePath: String): String {
val returnBuffer = StringBuilder()
val file = fopen(filePath, "r") ?:
throw IllegalArgumentException("Cannot open input file $filePath")
try {
memScoped {
val readBufferLength = 64 * 1024
val buffer = allocArray<ByteVar>(readBufferLength)
var line = fgets(buffer, readBufferLength, file)?.toKString()
while (line != null) {
returnBuffer.append(line)
line = fgets(buffer, readBufferLength, file)?.toKString()
}
}
} finally {
fclose(file)
}
return returnBuffer.toString()
}
}