Skip to content

demo

计算文件行数

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {

    if len(os.Args) < 2 {
        return
    }

    filename := os.Args[1]

    file, err := os.Open(filename)

    if err != nil {
        fmt.Println(err)
        return
    }

    // defer 延时,整个main执行完之后执行
    defer file.Close()

    reader := bufio.NewReader(file)

    var line int
    for {
        _, isPrefix, err := reader.ReadLine()

        if err != nil {
            break
        }

        if !isPrefix {
            line++
        }

    }
    fmt.Println(line)
}

// 输出
MacintoshdeMacBook-Pro-139:counter elasticnotes$ go run count.go
43