写入文件突然停止

时间:2019-12-04 09:39:04

标签: go printf

我正在尝试解析文本文件并将所有带有'second(s)'字的行写入另一个文件

func main() {
    logFile, e := os.Open(os.Args[1])
    checkError(e)
    defer logFile.Close()
    scanner := bufio.NewScanner(logFile)
    parsedLogFile, e := os.Create(os.Args[2])
    checkError(e)
    defer parsedLogFile.Close()
    toParsedLog := bufio.NewWriter(parsedLogFile)
    regexpSeconds := regexp.MustCompile(`(\d+)?(\.)?\d+? +second(s)?`)
    for scanner.Scan() {
        checkError(scanner.Err())
        if regexpSeconds.MatchString(scanner.Text()) {
            regexStart := regexpSeconds.FindStringIndex(scanner.Text())
            description := scanner.Text()[0:regexStart[0]]
            time := scanner.Text()[regexStart[0]:]
            fmt.Fprintf(toParsedLog, "|%-100s|%-40s|\n", description, time)
            fmt.Printf("|%-100s|%-40s|\n", description, time)
        }
    }
}

问题是文件突然结束,并且在创建的文件中没有所有行。 我将文件内容与Printf控制台输出进行了比较

文件结尾看起来像这样:

|foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar                |0.221822 seconds blah blah blah blah      |
|foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar                              |0.02 seconds               ^ 

如您所见,没有最后一个|在输出中。 ^是文件的结尾。

我的代码有问题吗?我该如何解决?

0 个答案:

没有答案