douxian7534 2018-03-15 21:22
浏览 42
已采纳

没有输出到错误文件

I'm coding a little Go program. It reads files in a directory line by line, it only reads lines with a certain prefix, normalizes the data and outputs to one of two files, depending on whether the normalized record has certain number of elements.

Data is being outputted to the Data file, but errors are not being outputted to the Errors file.

Debugging I see no issue.

Any help is much appreciated.

Thanks,

Martin

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "strings"
)

func main() {

    //Output file - Data
    if _, err := os.Stat("allData.txt"); os.IsNotExist(err) {

        var file, err = os.Create("allData.txt")

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

    file, err := os.OpenFile("allData.txt", os.O_WRONLY|os.O_APPEND, 0644)
    if err != nil {
        panic(err)
    }

    w := bufio.NewWriter(file)

    //Output file - Errors
    if _, err := os.Stat("errorData.txt"); os.IsNotExist(err) {

        var fileError, err = os.Create("errorData.txt")

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

    fileError, err := os.OpenFile("errorData.txt", os.O_WRONLY|os.O_APPEND, 0644)
    if err != nil {
        panic(err)
    }

    z := bufio.NewWriter(fileError)

    //Read Directory
    files, err := ioutil.ReadDir("../")
    if err != nil {
        log.Fatal(err)
    }

    //Build file path
    for _, f := range files {
        fName := string(f.Name())
        sPath := string("../" + fName)
        sFile, err := os.Open(sPath)
        if err != nil {
            fmt.Println(err)            
            return
        }

        //Create scanner
        scanner := bufio.NewScanner(sFile)
        scanner.Split(bufio.ScanLines)
        var lines []string
        // This is the buffer now
        for scanner.Scan() {
            lines = append(lines, scanner.Text())
        }
        for _, line := range lines {

            sRecordC := strings.HasPrefix((line), "DATA:")

            if sRecordC {
                splitted := strings.Split(line, " ")
                splittedNoSpaces := deleteEmpty(splitted)

                if len(splittedNoSpaces) == 11 {
                    splittedString := strings.Join(splittedNoSpaces, " ")
                    sFinalRecord := string(splittedString + "
")
                    if _, err = fmt.Fprintf(w, sFinalRecord); err != nil {
                    }
                }
                if len(splittedNoSpaces) < 11 {
                    splitted := strings.Split(line, " ")
                    splittedNoSpaces := deleteEmpty(splitted)
                    splittedString := strings.Join(splittedNoSpaces, " ")
                    sFinalRecord := string(splittedString + "
")
                    if _, err = fmt.Fprintf(z, sFinalRecord); err != nil {
                    }

                    err = fileError.Sync()
                    if err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
    err = file.Sync()
    if err != nil {
        log.Fatal(err)
    }
}

//Delete Empty array elements
func deleteEmpty(s []string) []string {
    var r []string
    for _, str := range s {
        if str != "" {
            r = append(r, str)
        }
    }
    return r
}
  • 写回答

1条回答 默认 最新

  • doutuo2829 2018-03-15 21:49
    关注

    Don't open the file multiple times, and don't check for the file's existence before creating it, just use the os.O_CREATE flag. You're also not deferring the correct os.File.Close call, because it's opened multiple times.

    When using a bufio.Writer, you should always call Flush() to ensure that all data has been written to the underlying io.Writer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line