Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go写文件实例
Go写文件实例
作者:--    发布时间:2019-11-20

在go中写入文件与读取文件的模式类似。首先我们来看一些读取文件的例子。写入文件需要检查大多数调用错误。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

writing-files.go的完整代码如下所示 -

package main

import (
    "bufio"
    "fmt"
    "io/ioutil"
    "os"
)

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

func main() {

    // to start, here's how to dump a string (or just
    // bytes) into a file.
    d1 := []byte("hello\ngo\n")
    err := ioutil.writefile("dat1.txt", d1, 0644)
    check(err)

    // for more granular writes, open a file for writing.
    f, err := os.create("dat2.txt")
    check(err)

    // it's idiomatic to defer a `close` immediately
    // after opening a file.
    defer f.close()

    // you can `write` byte slices as you'd expect.
    d2 := []byte{115, 111, 109, 101, 10}
    n2, err := f.write(d2)
    check(err)
    fmt.printf("wrote %d bytes\n", n2)

    // a `writestring` is also available.
    n3, err := f.writestring("writes\n")
    fmt.printf("wrote %d bytes\n", n3)

    // issue a `sync` to flush writes to stable storage.
    f.sync()

    // `bufio` provides buffered writers in addition
    // to the buffered readers we saw earlier.
    w := bufio.newwriter(f)
    n4, err := w.writestring("buffered\n")
    fmt.printf("wrote %d bytes\n", n4)

    // use `flush` to ensure all buffered operations have
    // been applied to the underlying writer.
    w.flush()

}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run writing-files.go
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册