Skip to content

doloopwhile/go-fileinput

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status

fileinput

-- import "github.com/doloopwhile/go-fileinput"

An analogous article of fileinput module in Python

Examples:

// reverse.go
// print file lines in reverse order.
package main

import (
	"fmt"
	"os"

	"github.com/doloopwhile/go-fileinput"
)

func main() {
	sc := fileinput.Lines(os.Args[1:])
	lines := []string{}
	for sc.Scan() {
		l := sc.Text()
		lines = append(lines, l)
	}
	if sc.Err() != nil {
		os.Stderr.WriteString(sc.Err().Error() + "\n")
		os.Exit(1)
	}
	for i := len(lines) - 1; i >= 0; i-- {
		fmt.Printf("%02d: %s\n", i+1, lines[i])
	}
}

Usage

func StdOpen

func StdOpen(name string) (io.ReadCloser, error)

StdOpen open file with os.Open. However, it returns os.Stdin for "-".

type Scanner

type Scanner struct {
	Args      []string                                 // Names of files. It should be os.Args[1:] in typical use case.
	Open      func(name string) (io.ReadCloser, error) // Function to open files.
	SplitFunc bufio.SplitFunc                          // Argument of Split() of bufio.Split.
}

Scanner provides a interface like bufio.Scanner to reading data from multiple files.

It is not expected that members of Scanner is modified after first call of .Scan() If it was, it is undefined what happen.

func Lines

func Lines(args []string) *Scanner

Lines returns a new Scanner to read lines of files in args. If args is empty, it return a Scanner which scans os.Stdin.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns the first non-EOF error that was encountered by the Scanner or was returned by Open.

func (*Scanner) Scan

func (s *Scanner) Scan() bool

Scan advances internal scanner to the next token like Scan method of bufio.Scanner. It automatically open/close files specified in Args.

func (*Scanner) Text

func (s *Scanner) Text() string

Text returns the most recent token generated by a call to Scan as a newly allocated string holding its bytes.

About

An analogous article of fileinput module in Python

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages