Reading files _ golang

Reading and writing files are basic tasks needed for many Go programs. First we'll look at some examples of reading files

package main

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

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

func main() {

    dat, err := ioutil.ReadFile("/tmp/dat")
    check(err)
    fmt.Println(string(dat))

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

    b1 := make([]byte, 5)
    n1, err := f.Read(b1)
    check(err)
    fmt.Println("%d bytes: %s\n", n1, string(b1))

    o2, err := f.Seek(6, 0)
    check(err)
    b2 := make([]byte, 2)
    n2, err := f.Read(b2)
    check(err)
    fmt.Println("%d bytes @ %d: %s\n", n2, o2, string(b2))

    o3, err := f.Seek(6, 0)
    check(err)
    b3 := make([]byte, 2)
    n3, err := io.ReadAtLeast(f, b3, 2)
    check(err)
    fmt.Println("%d bytes @ %d: %s\n", n3, o3, string(b3))

    _, err = f.Seek(0, 0)
    check(err)

    r4 := bufio.NewReader(f)
    b4, err := r4.Peek(5)
    check(err)
    fmt.Println("5 bytes: %s\n", string(b4))

    f.Close()

}
xjk in usa 2030 

%d bytes: %s
 5 xjk i
%d bytes @ %d: %s
 2 6  u
%d bytes @ %d: %s
 2 6  u
5 bytes: %s
 xjk i

总结 : 

  1 : ...

本文来自:博客园

感谢作者:jackkiexu

查看原文:Reading files _ golang

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