在线文档  >   Golang练习   >   写文件

在Go中编写文件遵循与我们之前看到的读取类似的模式。

package main

import (
    "bufio"
    "fmt"
    "os"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    //首先,这是如何将字符串(或仅字节)转储到文件中。
    d1 := []byte("hello\ngo\n")
    err := os.WriteFile("/tmp/dat1", d1, 0644)
    check(err)

    // 为了进行更精细的写入,打开一个要写入的文件。
    f, err := os.Create("/tmp/dat2")
    check(err)

    // 打开文件后立即使用`Close`进行惯用推迟。
    defer f.Close()

    // 您可以像预期的那样`Write`字节片。
    d2 := []byte{115, 111, 109, 101, 10}
    n2, err := f.Write(d2)
    check(err)
    fmt.Printf("wrote %d bytes\n", n2)

    // `WriteString`也可用。
    n3, err := f.WriteString("writes\n")
    check(err)
    fmt.Printf("wrote %d bytes\n", n3)

    // 发出`Sync`以将写入刷新到稳定存储。
    f.Sync()

    // 除了我们之前看到的缓冲读取器之外,`bufio`还提供了缓冲写入器。
    w := bufio.NewWriter(f)
    n4, err := w.WriteString("buffered\n")
    check(err)
    fmt.Printf("wrote %d bytes\n", n4)

    // 使用`Flush`确保所有缓冲操作都已应用于底层写入器。
    w.Flush()

}

运行结果如下:

$ go run writing-files.go 
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

# 检查写入文件的内容。
$ cat /tmp/dat1
hello
go
$ cat /tmp/dat2
some
writes
buffered

我们刚刚看到了文件 I/O 思想, 接下来,我们看看它在 stdin 和 stdout 流中的应用。