input: Standardized input module added.

This commit is contained in:
jienfak 2020-03-23 21:12:50 +05:00
parent 722947a2cd
commit 54a9f10120
3 changed files with 45 additions and 21 deletions

39
input/read.go Normal file
View file

@ -0,0 +1,39 @@
package input
import (
"os"
"io"
"bufio"
)
func ReadAllRaw(f *os.File) ([]byte, error) {
ret := make([]byte, 0)
b := make([]byte, 512)
for {
n, e := f.Read(b)
if n>0 {
ret = append(ret, b[:n]...)
}
if e == io.EOF {
break
}else if e != nil {
return nil, e
}
}
return ret, nil
}
func ReadAllLines(f *os.File)( []string, error ){
r := bufio.NewReader(f)
a := make([]string, 0)
for {
l, e := r.ReadString('\n')
if e==io.EOF {
break
}else if e != nil {
return nil, e
}
a = append(a, l)
}
return a, nil
}

View file

@ -1,37 +1,23 @@
package sort
import (
"bufio"
"fmt"
"os"
"sort"
"io"
"flag"
"github.com/jienfak/goblin/input"
)
func ReadLines() []string {
r := bufio.NewReader(os.Stdin)
a := make([]string, 0)
for {
l, e := r.ReadString('\n')
if e==io.EOF {
break
}
a = append(a, l)
}
return a
}
func Run(args []string) int {
flagSet := flag.NewFlagSet(args[0], flag.ExitOnError)
flagSet.Parse(args[1:])
status := 0
lines := ReadLines()
lines, _ := input.ReadAllLines(os.Stdin)
sort.Strings(lines)
for _, l := range lines {
fmt.Print(l)
}
return status
}

View file

@ -6,7 +6,7 @@ import(
"fmt"
"flag"
"strings"
"github.com/jienfak/goblin/sort"
"github.com/jienfak/goblin/input"
)
func yes(s string){
@ -30,14 +30,13 @@ func Run(args []string) int {
flagSet.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s: %s [options] [string]\n", arg0, arg0)
flagSet.PrintDefaults()
}
flagSet.Parse(args)
args = flagSet.Args()
if stdinFlag {
in := sort.ReadLines()
s = strings.Join(in, "")
in, _ := input.ReadAllRaw(os.Stdin)
s = string(in)
} else {
if len(args)>0 {
s = strings.Join(args, " ")