writing files _ golang

Writing files in Go follows similar patterns to the ones we saw earlier for reading

package main

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

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

func main() {

    d1 := []byte("hello\ngo\n")
    err := ioutil.WriteFile("/tmp/dat", d1, 0644)
    check(err)

    f, err := os.Create("/tmp/dat")
    check(err)

    defer f.Close()

    d2 := []byte{115, 111, 109, 101, 10}
    n2, err := f.Write(d2)
    check(err)
    fmt.Println("wrote %d bytes\n", n2)

    n3, err := f.WriteString("writes\n")
    fmt.Println("wrote %d bytes\n", n3)

    f.Sync()

    w := bufio.NewWriter(f)
    n4, err := w.WriteString("buffered\n")
    fmt.Println("wrote %d bytes\n", n4)

    w.Flush()
}
wrote %d bytes
 5
wrote %d bytes
 7
wrote %d bytes
 9

总结 : 

  1 : ....

本文来自:博客园

感谢作者:jackkiexu

查看原文:writing files _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。