64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package q5
|
|
|
|
import "io"
|
|
import "os"
|
|
import "bufio"
|
|
import "strings"
|
|
|
|
type CsvReader struct {
|
|
columns map[string]int32
|
|
values []string
|
|
|
|
currLine int
|
|
lines []string
|
|
}
|
|
|
|
func (this *CsvReader) Load(fileName string) bool {
|
|
this.columns = map[string]int32{}
|
|
this.values = []string{}
|
|
this.currLine = 0
|
|
this.lines = []string{}
|
|
|
|
f, err := os.Open(fileName)
|
|
if err == nil {
|
|
defer f.Close()
|
|
|
|
br := bufio.NewReader(f)
|
|
for {
|
|
line, _, c := br.ReadLine()
|
|
if c == io.EOF {
|
|
break
|
|
}
|
|
this.lines = append(this.lines, string(line))
|
|
}
|
|
}
|
|
return err == nil
|
|
}
|
|
|
|
func (this *CsvReader) NextLine() bool {
|
|
if this.currLine >= len(this.lines) {
|
|
return false
|
|
}
|
|
this.values = strings.Split(this.lines[this.currLine], ",")
|
|
this.currLine++
|
|
return true
|
|
}
|
|
|
|
func (this *CsvReader) GetValue(fieldName string) *XValue {
|
|
index, ok := this.columns[fieldName]
|
|
if ok {
|
|
if index >= 0 && index < int32(len(this.values)) {
|
|
return (&XValue{}).SetString(this.values[index])
|
|
} else {
|
|
return &XValue{}
|
|
}
|
|
} else {
|
|
return &XValue{}
|
|
}
|
|
}
|
|
|
|
func (this *CsvReader) KeyExists(fieldName string) bool {
|
|
_, ok := this.columns[fieldName]
|
|
return ok
|
|
}
|