从文件中获取倒数第二行

时间:2016-11-03 17:45:44

标签: string go

我找到了一个方法如何读取文件中的最后一行,但是我文件中的最后一行是空的,我需要阅读倒数第二行,我不知道该怎么做,请帮助一下。

func ll(z string) string {

    f, err := os.Open(z)
    if err != nil {
        log.Fatal(err)
    }
    bf := bufio.NewReader(f)
    for {
        switch line, err := bf.ReadString('\n'); err {
        case nil:
        // valid line, echo it.  note that line contains trailing \n.
        fmt.Println(line)

        case io.EOF:
            if line > "" {
                // last line of file missing \n, but still valid
                    fmt.Println(line, "in func")
            }
            return  line
        default:
            log.Fatal(err)
        }
    }
}

1 个答案:

答案 0 :(得分:2)

每次迭代都只保存当前行,这样当你遇到最后一行时,你可以返回prev_line

func next_to_last(z string) string {
    f, err := os.Open(z)
    if err != nil {
        log.Fatal(err)
    }
    bf := bufio.NewReader(f)
    prev_line := ""

    for {
        switch line, err := bf.ReadString('\n'); err {

        case nil:
        // valid line, echo it.  note that line contains trailing \n.
        fmt.Println(line)
        prev_line = line // Save line as previous

        case io.EOF:
            if line > "" {
                // last line of file missing \n, but still valid
                    fmt.Println(line, "in func")
            }
            return  prev_line // Return previous line

        default:
            log.Fatal(err)
        }
    }
}