在字符串数组中读取(和写入)文本文件的能力我认为是一个相当普遍的要求。当开始使用一种无需访问数据库的语言时,它也非常有用。Golang里有吗? 例如
func ReadLines(sFileName string, iMinLines int) ([]string, bool) {
和
func WriteLines(saBuff[]string, sFilename string) (bool) {
我宁愿使用现有的而不是重复的。
从 Go1.1 版本开始,有一个bufio.Scanner API 可以轻松地从文件中读取行。考虑上面的以下示例,用 Scanner 重写:
package main import ( "bufio" "fmt" "log" "os" ) // readLines reads a whole file into memory // and returns a slice of its lines. func readLines(path string) ([]string, error) { file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() var lines []string scanner := bufio.NewScanner(file) for scanner.Scan() { lines = append(lines, scanner.Text()) } return lines, scanner.Err() } // writeLines writes the lines to the given file. func writeLines(lines []string, path string) error { file, err := os.Create(path) if err != nil { return err } defer file.Close() w := bufio.NewWriter(file) for _, line := range lines { fmt.Fprintln(w, line) } return w.Flush() } func main() { lines, err := readLines("foo.in.txt") if err != nil { log.Fatalf("readLines: %s", err) } for i, line := range lines { fmt.Println(i, line) } if err := writeLines(lines, "foo.out.txt"); err != nil { log.Fatalf("writeLines: %s", err) } }