head and tail are working.

master
Zed A. Shaw 1 week ago
parent f54892934f
commit cd6f70d1fe
  1. 2
      head/.gitignore
  2. 4
      head/Makefile
  3. 3
      head/go.mod
  4. 43
      head/main.go
  5. 2
      tail/.gitignore
  6. 4
      tail/Makefile
  7. 3
      tail/go.mod
  8. 47
      tail/main.go

2
head/.gitignore vendored

@ -0,0 +1,2 @@
head
head.exe

@ -0,0 +1,4 @@
build:
go build .

@ -0,0 +1,3 @@
module lcthw.dev/go/go-coreutils/head
go 1.25.3

@ -0,0 +1,43 @@
package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func HeadFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
for cur_line := 0; scan.Scan(); cur_line++ {
line := scan.Text()
if cur_line < count {
fmt.Println(line)
}
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
}
func main() {
var count int
flag.IntVar(&count, "n", 10, "number of lines")
flag.Parse()
if flag.NArg() > 0 {
files := flag.Args()
for _, fname := range files {
file, err := os.Open(fname)
if err != nil { log.Fatal(err) }
HeadFile(file, count)
}
} else {
HeadFile(os.Stdin, count)
}
}

2
tail/.gitignore vendored

@ -0,0 +1,2 @@
tail
tail.exe

@ -0,0 +1,4 @@
build:
go build .

@ -0,0 +1,3 @@
module lcthw.dev/go/go-coreutils/tail
go 1.25.3

@ -0,0 +1,47 @@
package main
import (
"fmt"
"bufio"
"os"
"log"
"flag"
"io"
)
func TailFile(file io.Reader, count int) {
scan := bufio.NewScanner(file)
var lines []string
for scan.Scan() {
lines = append(lines, scan.Text())
}
if scan.Err() != nil { log.Fatal(scan.Err()) }
start := len(lines) - count
if start < 0 { start = 0 }
for line := int(start); line < len(lines); line++ {
fmt.Println(lines[line])
}
}
func main() {
var count int
flag.IntVar(&count, "n", 10, "number of lines")
flag.Parse()
if flag.NArg() > 0 {
files := flag.Args()
for _, fname := range files {
file, err := os.Open(fname)
if err != nil { log.Fatal(err) }
TailFile(file, count)
}
} else {
TailFile(os.Stdin, count)
}
}
Loading…
Cancel
Save