I am writing a simple fxn that counts line numbers:
func GetNumberOfLines(file io.Reader) (numberOfLines int, err error) { scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanLines) for scanner.Scan() { numberOfLines++ } return numberOfLines, nil } In a test run, when I dynamically create a temporary file the fxn fails to count the number and returns 0
const fileContents = `Here is a line and here is another line and a third one` func main() { file, err := ioutil.TempFile("/tmp", "") if err != nil { panic(err) } _, err = file.Write([]byte(fileContents)) if err != nil { panic(err) } lineNo, err := GetNumberOfLines(file) if err != nil { panic(err) } print(lineNo) } ▶ go run main.go 0 If However I pass the file that was previously created explicitly, the fxn does count the numbers correctly:
func main() { file, err := os.Open("/tmp/742665138") if err != nil { panic(err) } lineNo, err := GetNumberOfLines(file) if err != nil { panic(err) } print(lineNo) } ▶ go run main.go 3 Why in the case of the dynamic tmp file creation the GetNumberOfLines fails to count the lines?
没有评论:
发表评论