package xio import ( "bufio" "fmt" "io" "os" "strings" ) // OpenTwo opens two files. The caller needs to check for a single error only. func OpenTwo(f1, f2 string) (g1, g2 *os.File, err error) { if g1, err = os.Open(f1); err != nil { return nil, nil, err } if g2, err = os.Open(f2); err != nil { return nil, nil, err } return g1, g2, nil } func TabsToMapFile(filename, sep string, kCol, vCol int) (map[string]string, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() return TabsToMap(f, sep, kCol, vCol) } // TabsToMap read from a reader and turns values from kCol, vCol columns into a // mapping. func TabsToMap(r io.Reader, sep string, kCol, vCol int) (map[string]string, error) { var ( br = bufio.NewReader(r) m = make(map[string]string, 8388608) line, k, v string fields []string err error ) for { line, err = br.ReadString('\n') if err == io.EOF { return m, nil } if err != nil { return nil, err } fields = strings.Split(line, sep) if len(fields) > kCol-1 && len(fields) > vCol-1 { k = strings.TrimSpace(fields[kCol-1]) v = strings.TrimSpace(fields[vCol-1]) m[k] = v } else { return nil, fmt.Errorf("invalid line: %v (%v fields, %v, %v)", line, len(fields), kCol, vCol) } } return m, nil }