Misc tweaks (#387)

This commit is contained in:
Nikolay Igotti
2017-03-25 11:35:56 +03:00
committed by GitHub
parent 16b076f46d
commit af3b74451d
19 changed files with 254 additions and 46 deletions
+56
View File
@@ -0,0 +1,56 @@
import kotlinx.cinterop.*
import stdio.*
fun parseLine(line: String, separator: Char) : List<String> {
val result = mutableListOf<String>()
var builder = StringBuilder()
var quotes = 0
for (ch in line) {
when {
ch == '\"' -> {
quotes++
builder.append(ch)
}
(ch == '\n') || (ch == '\r') -> {}
(ch == separator) && (quotes % 2 == 0) -> {
result.add(builder.toString())
builder = StringBuilder()
}
else -> builder.append(ch)
}
}
return result
}
fun main(args: Array<String>) {
if (args.size != 3) {
println("usage: csvparser.kexe file.csv column count")
return
}
val fileName = args[0]
val column = args[1].toInt()
val count = args[2].toInt()
val file = fopen(fileName, "r")
if (file == null) {
perror("cannot open input file $fileName")
return
}
try {
memScoped {
val bufferLength = 64 * 1024
val buffer = allocArray<CInt8Var>(bufferLength)
for (i in 1..count) {
val nextLine = fgets(buffer[0].ptr, bufferLength, file)?.toKString()
if (nextLine == null || nextLine.isEmpty()) break
val records = parseLine(nextLine, ',')
println(records[column])
}
}
} finally {
fclose(file)
}
}
File diff suppressed because one or more lines are too long
+14
View File
@@ -0,0 +1,14 @@
# CVS parser
This example shows how one could implement simple CSV reader and parser in Kotlin.
A sample data [European Mammals Red List for 2009] (https://data.europa.eu/euodp/en/data/dataset?res_format=CSV)
from EU is being used.
To build use `./build.sh` script without arguments (or specify `TARGET` variable if cross-compiling).
To run use
./CsvParser.kexe ./European_Mammals_Red_List_Nov_2009.csv 4 100
Which will print fifth column (Family, zero-based index) in first 100 rows of the
CSV file.
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env bash
DIR=.
PATH=../../dist/bin:../../bin:$PATH
if [ x$TARGET == x ]; then
case "$OSTYPE" in
darwin*) TARGET=macbook ;;
linux*) TARGET=linux ;;
*) echo "unknown: $OSTYPE" && exit 1;;
esac
fi
var=CFLAGS_${TARGET}
CFLAGS=${!var}
var=LINKER_ARGS_${TARGET}
LINKER_ARGS=${!var}
var=COMPILER_ARGS_${TARGET}
COMPILER_ARGS=${!var} # add -opt for an optimized build.
interop -def:$DIR/stdio.def -copt:"$CFLAGS" -target:$TARGET || exit 1
konanc $COMPILER_ARGS -target $TARGET $DIR/CsvParser.kt stdio -nativelibrary stdiostubs.bc -o CsvParser.kexe || exit 1
+3
View File
@@ -0,0 +1,3 @@
headers = stdio.h stdlib.h string.h
compilerOpts = -D_POSIX_SOURCE
excludedFunctions =