dongqi7631 2018-02-02 20:04
浏览 233

Golang读取文件回车

Hi i have a implementation to read a file Line Feed, but it does not work to Carriage Return files the implementation is:

file, err := os.Open(filePath)
    if err != nil {
        ross := int32(1)
        fileValidation = append(fileValidation, p.createPharmacyPanelLoaderResultErr(pharmacyPanel, &ross, err.Error(), err.Error()))
        return nil, fileValidation, int32(0)
    }

scanner := bufio.NewScanner(file)
for i := 0; scanner.Scan(); i++ {
 line := scanner.Text()
}

i want to transform this function to can work with both Carriage Return and Line Feed

  • 写回答

1条回答 默认 最新

  • doujia7094 2018-09-18 21:52
    关注

    I took the ScanLines function from the source code and changed it so it works with but now it will only work with and not or

    package main
    
    import (
        "bufio"
        "bytes"
        "fmt"
        "os"
    )
    
    func ScanLinesWithCR(data []byte, atEOF bool) (advance int, token []byte, err error) {
        if atEOF && len(data) == 0 {
            return 0, nil, nil
        }
        if i := bytes.IndexByte(data, ''); i >= 0 {
            // We have a full newline-terminated line.
            return i + 1, data[0:i], nil
        }
        // If we're at EOF, we have a final, non-terminated line. Return it.
        if atEOF {
            return len(data), data, nil
        }
        // Request more data.
        return 0, nil, nil
    }
    
    func main() {
        f, _ := os.Open("test.txt")
        defer f.Close()
        scanner := bufio.NewScanner(f)
        scanner.Split(ScanLinesWithCR)
        for scanner.Scan() {
            fmt.Println(">", scanner.Text())
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致