diff --git a/utio/lines.go b/utio/lines.go new file mode 100644 index 0000000..5f3b317 --- /dev/null +++ b/utio/lines.go @@ -0,0 +1,48 @@ +package utio + +import ( + "bufio" + "fmt" + "io" +) + +type Liner struct { + Lines []string +} + +// Lines creates a coder that encodes/decodes the lines of a text file. +func Lines() *Liner { + return &Liner{} +} + +func (l *Liner) Encode(w io.Writer) error { + for _, line := range l.Lines { + if _, err := fmt.Fprintln(w, line); err != nil { + return err + } + } + return nil +} + +func (l *Liner) Decode(r io.Reader) error { + scanner := bufio.NewScanner(r) + for scanner.Scan() { + l.Lines = append(l.Lines, scanner.Text()) + } + return scanner.Err() +} + +// ReadLines reads a text file and splits in lines. +func ReadLines(path string) ([]string, error) { + var l = Lines() + var err = DecodeFile(path, l) + if nil != err { + return nil, err + } + return l.Lines, nil +} + +// WriteLines writes lines to a text file. +func WriteLines(path string, lines []string) error { + return EncodeFile(path, &Liner{lines}) +}