First coreutil started, cat.

master
Zed A. Shaw 3 weeks ago
parent 1fe14dd2e4
commit 9412f1b074
  1. 3
      cat/go.mod
  2. 43
      cat/main.go

@ -0,0 +1,3 @@
module git.learnjsthehardway.com/learn-code-the-hard-way/go-coreutils/cat
go 1.24.2

@ -0,0 +1,43 @@
package main
import (
"fmt"
"flag"
"os"
"log"
"strings"
)
func Fail(err error, format string, v ...any) {
err_format := fmt.Sprintf("ERROR: %v; %s", err, format)
log.Printf(err_format, v...)
os.Exit(1)
}
func main() {
var number bool
flag.BoolVar(&number, "n", false, "Number all nonempty output lines, starting with 1")
flag.BoolVar(&number, "number", false, "Number all nonempty output lines, starting with 1")
flag.Parse()
if flag.NArg() < 1 {
log.Fatal("USAGE: cat [-n/--number] file0 [fileN]")
os.Exit(1)
}
filename := flag.Arg(0)
in_file, err := os.ReadFile(filename)
if err != nil { Fail(err, "cannot open %s:", filename) }
if(number) {
count := 1
for line := range strings.Lines(string(in_file)) {
fmt.Printf("%0.4d: %s", count, line)
count++
}
} else {
fmt.Print(string(in_file))
}
}
Loading…
Cancel
Save