|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
func numberOfBytes(args []string) (int, []string) {
|
|
|
|
n := len(args)
|
|
|
|
nbytes := 0
|
|
|
|
var files []string
|
|
|
|
for i, v := range args {
|
|
|
|
var err error
|
|
|
|
_, err = strconv.Atoi(v)
|
|
|
|
if v == "-c" {
|
|
|
|
if i >= n-1 {
|
|
|
|
fmt.Printf("tail: option requires an argument -- 'c'\nTry 'tail --help' for more information.")
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
arg := args[i+1]
|
|
|
|
|
|
|
|
nbytes, err = strconv.Atoi(arg)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("tail: invalid number of bytes: `%s`\n", arg)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
files = append(files, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nbytes, files
|
|
|
|
}
|
|
|
|
|
|
|
|
func fileSize(fi *os.File) int64 {
|
|
|
|
fil, err := fi.Stat()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return fil.Size()
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
n := len(os.Args)
|
|
|
|
if n < 4 {
|
|
|
|
fmt.Println("Not enough arguments")
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
nbytes, files := numberOfBytes(os.Args[1:])
|
|
|
|
|
|
|
|
printName := len(files) > 1
|
|
|
|
|
Refactor & Beautify & destruction commit
return early, remove else branches, reorder conditions and top-level functions, remove empty lines, remove unnecessary append(), fix typos, stop using testing package, remove dead code, fix mistakes in subjects, tests and solutions, remove disclaimers, reformat comments, simplify solutions, tests, add more instructions to subjects, remove obsolete files, etc.
Some of the reasons behind those modifications will be added to good-practices.en.md
Some of the exercises are now broken, they will have to be fixed, most of them have a "TODO:" comment.
5 years ago
|
|
|
// open files for reading only
|
|
|
|
for j, f := range files {
|
|
|
|
fi, err := os.Open(f)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("tail: cannot open '%s' for reading: No such file or directory\n", f)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
if printName {
|
|
|
|
fmt.Printf("==> %s <==\n", f)
|
|
|
|
}
|
|
|
|
read := make([]byte, int(nbytes))
|
|
|
|
_, er := fi.ReadAt(read, fileSize(fi)-int64(nbytes))
|
|
|
|
if er != nil {
|
|
|
|
fmt.Println(er.Error())
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, c := range read {
|
|
|
|
fmt.Printf("%c", rune(c))
|
|
|
|
}
|
|
|
|
|
|
|
|
if j < len(files)-1 {
|
|
|
|
fmt.Println()
|
|
|
|
}
|
|
|
|
|
|
|
|
fi.Close()
|
|
|
|
}
|
|
|
|
}
|