mchirico / zDaily

Playground to hack and test ideas with Zoe
1 stars 2 forks source link

Day 35: I/O #39

Open mchirico opened 3 years ago

mchirico commented 3 years ago

video

Reading and Writing to Files

Samples to build from

package main

import "os"

func Write(file, txt string) {
    f, err := os.Create(file)
    if err != nil {
        return
    }
    defer f.Close()
    f.Write([]byte(txt))
}

func main() {
    Write("junk.txt", "this is junk")
}

Note, you can also append

package main

import "os"

func WriteAppend(file, txt string) {
    f, err := os.OpenFile(file,
        os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return
    }
    defer f.Close()
    f.Write([]byte(txt))
}

func main() {
    WriteAppend("junk.txt", "this is junk")
}

Here's an example reading... note you have to specify number of bytes in b

package main

import (
    "fmt"
    "os"
)

func WriteAppend(file, txt string) {
    f, err := os.OpenFile(file,
        os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return
    }
    defer f.Close()
    f.Write([]byte(txt))
}

func Read(file string,b []byte) (int, error) {
    f, err := os.OpenFile(file,
        os.O_RDWR, 0644)
    if err != nil {
        return 0,err
    }
    defer f.Close()

    return f.Read(b)
}

func main() {
    WriteAppend("junk.txt", "this is junk")
    b := make([]byte,3)
    Read("junk.txt",b)
    fmt.Printf("b: %s\n",b)
}
package main

import (
    "fmt"
    "os"
)

func WriteAppend(file, txt string) {
    f, err := os.OpenFile(file,
        os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        return
    }
    defer f.Close()
    f.Write([]byte(txt))
}

func Read(file string, b []byte) (int, error) {
    f, err := os.OpenFile(file,
        os.O_RDWR, 0644)
    if err != nil {
        return 0, err
    }
    defer f.Close()

    return f.Read(b)
}

func main() {
    for i := 0; i < 30; i++ {
        WriteAppend("junk.txt", "this is junk\n")
    }
    b := make([]byte, 3)
    Read("junk.txt", b)
    fmt.Printf("b: %s\n", b)

}
tacomonkautobot[bot] commented 3 years ago

mchirico, Thanks for opening this issue!

ZoeChiri commented 3 years ago

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {

    junk := []byte("here is my file. greygraypuff is chonky")
    err := ioutil.WriteFile("myjunkfile.data", junk, 3000)

    if err != nil {

        fmt.Println(err)
    }

    data, err := ioutil.ReadFile("myjunkfile.data")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Print(string(data))

}