您好我有一个实现读取文件换行符,但它不适用于Carriage Return文件,实现是:
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()
}
我想将此功能转换为可以使用回车符和换行符
答案 0 :(得分:0)
我从源代码中获取了ScanLines函数,并对其进行了更改,因此它可以与\ r一起使用,但现在仅适用于\ r而不是\ n或\ r \ n
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, '\r'); 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())
}
}