ZhangZhihui's Blog  

 

package main

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

func main() {
    buffer := []byte("Data to write\n")

    f1, err := os.Create("f1.txt")
    if err != nil {
        fmt.Println("Cannot create f1:", err)
        os.Exit(1)
    }
    defer f1.Close()
    fmt.Fprint(f1, string(buffer))

    f2, err := os.Create("f2.txt")
    if err != nil {
        fmt.Println("Cannot create f2:", err)
        os.Exit(1)
    }
    defer f2.Close()
    n, err := f2.WriteString(string(buffer))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Printf("wrote %d bytes\n", n)

    f3, err := os.Create("f3.txt")
    if err != nil {
        fmt.Println("Cannot create f3:", err)
        os.Exit(1)
    }
    defer f3.Close()
    w := bufio.NewWriter(f3)
    n, err = w.WriteString(string(buffer))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Printf("wrote %d bytes\n", n)
    w.Flush()

    f4, err := os.Create("f4.txt")
    if err != nil {
        fmt.Println("Cannot create f4:", err)
        os.Exit(1)
    }
    defer f4.Close()
    for i := 0; i < 5; i++ {
        n, err = io.WriteString(f4, string(buffer))
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
        fmt.Printf("wrote %d bytes\n", n)
    }

    // Append to a file
    f4, err = os.OpenFile("f4.txt", os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0644)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    defer f4.Close()
    // Write() needs a byte slice
    n, err = f4.Write([]byte("Put some more data at the end.\n"))
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Printf("wrote %d bytes\n", n)
}

 

posted on 2024-06-12 14:37  ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报