Video Coming Soon...

Created by Zed A. Shaw Updated 2025-10-23 14:49:14

39: head and tail

This exercise is pending. Quick notes about this exercise:

The head Code

View Source file go-coreutils/head/main.go Only

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)
  }
}

The tail Code

View Source file go-coreutils/tail/main.go Only

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)
  }
}
Previous Lesson Next Lesson

Register for Learn Go the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.