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 package sort
import ( import (
"bufio"
"fmt" "fmt"
"os" "os"
"sort" "sort"
"io"
"flag" "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 { func Run(args []string) int {
flagSet := flag.NewFlagSet(args[0], flag.ExitOnError) flagSet := flag.NewFlagSet(args[0], flag.ExitOnError)
flagSet.Parse(args[1:]) flagSet.Parse(args[1:])
status := 0 status := 0
lines := ReadLines() lines, _ := input.ReadAllLines(os.Stdin)
sort.Strings(lines) sort.Strings(lines)
for _, l := range lines { for _, l := range lines {
fmt.Print(l) fmt.Print(l)
} }
return status return status
} }

View file

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