go - 将文本文件读入字符串数组(并写入)

标签 go

我认为能够在字符串数组中读取(和写入)文本文件是一个相当普遍的要求。当从不需要访问数据库的语言开始时,它也非常有用。 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)
    }
}

关于go - 将文本文件读入字符串数组(并写入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5884154/

相关文章:

go - 记录 Golang 程序的惯用方式,由一个 main.go 文件组成

mongodb - 这些是 mgo 的相同版本/发行版吗?

python - 从 bash 到 GO 服务器的 REST post 查询有效但对于 Python 失败

postgresql - Golang结构的Postgres数组

templates - 文本/模板 : space in map's key

go - 如何使用 go 服务(正确地)一个 react-router?

json - JSON 字符串的交集

go - 如何在 Golang 的回调中使用接口(interface)?

go - Go 中的 SASS 渲染

go - 为什么golang软件包bcrypt在哈希密码后能够检索盐?