Source

go-play / cat.go

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"os"
)

func open(filename string) *bufio.Reader {
	var file *os.File

	if filename == "-" {
		file = os.Stdin
	} else {
		var err error
		file, err = os.Open(filename)
		if err != nil {
			panic(fmt.Sprintf("error: can't open %s", filename))
		}
	}

	return bufio.NewReader(file)
}

var lineNums = flag.Bool("n", false, "number lines")

func main() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			os.Exit(1)
		}
	}()

	flag.Parse()

	var files []string

	if flag.NArg() == 0 {
		files = []string{"-"}
	} else {
		files = flag.Args()
	}

	lnum := uint64(0)
	for _, filename := range files {
		file := open(filename)
		for {
			lnum++
			buf, err := file.ReadBytes('\n')
			if err == io.EOF {
				break
			}
			if err != nil {
				panic(fmt.Sprintf("%s error - %v", filename, err))
			}
			if *lineNums {
				fmt.Printf("%5d %s", lnum, buf)
			} else {
				fmt.Printf("%s", buf)
			}
		}
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.