user2443447
user2443447

Reputation: 151

split includes EOF?

I'm trying to run gopl.io/ch1/dup3 program from Donovan book on windows 7 using go version 1.7.3.

When I run the below program test.go, I get an empty line at the end. Is that for EOF? How do I distinguish it from an actual empty line?

package main
import (
  "fmt"
  "io/ioutil"
  "os"
  "strings"
)
func main() {
   Counts := make(map[string]int)
   for _, filename := range os.Args[1:] {
   data, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Fprintf(os.Stderr, "%s: %v\n", os.Args[0], err)
        continue
    }
    for _, line := range strings.Split(string(data), "\r\n") {
        counts[line]++
    }
  }
  for line, n := range counts {
    if n > 1 {
        fmt.Printf("%d\t%s\n", n, line)
    }
  }
}

with test.dat file:

Line number one
Line number two

Command:

> test.exe test.dat test.dat

Output is

2       Line number one  
2       Line number two  
2                           <-- Here is the empty line.

Upvotes: 0

Views: 556

Answers (1)

user539810
user539810

Reputation:

If your file ends with a newline sequence, splitting the file content on newline sequences will result in an extraneous empty string. If EOF occurred before a final newline sequence was read, then you don't get that empty string:

eofSlice := strings.Split("Hello\r\nWorld", "\r\n")
extraSlice := strings.Split("Hello\r\nWorld\r\n", "\r\n")

// [Hello World] 2
fmt.Println(eofSlice, len(eofSlice))

// [Hello World ] 3
fmt.Println(extraSlice, len(extraSlice))

Playground link

Upvotes: 1

Related Questions