Added Lines (lines of a file represented as a string slice).
This commit is contained in:
parent
491d976677
commit
fd774b775e
48
utio/lines.go
Normal file
48
utio/lines.go
Normal file
@ -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})
|
||||
}
|
Loading…
Reference in New Issue
Block a user