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

读取和写入文件是许多go程序所需的基本任务。首先我们来看一些读取文件的例子。读取文件需要检查大多数调用错误。

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

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

package main

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

// reading files requires checking most calls for errors.
// this helper will streamline our error checks below.
func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    // perhaps the most basic file reading task is
    // slurping a file's entire contents into memory.
    dat, err := ioutil.readfile("/tmp/dat")
    check(err)
    fmt.print(string(dat))

    // you'll often want more control over how and what
    // parts of a file are read. for these tasks, start
    // by `open`ing a file to obtain an `os.file` value.
    f, err := os.open("/tmp/dat")
    check(err)

    // read some bytes from the beginning of the file.
    // allow up to 5 to be read but also note how many
    // actually were read.
    b1 := make([]byte, 5)
    n1, err := f.read(b1)
    check(err)
    fmt.printf("%d bytes: %s\n", n1, string(b1))

    // you can also `seek` to a known location in the file
    // and `read` from there.
    o2, err := f.seek(6, 0)
    check(err)
    b2 := make([]byte, 2)
    n2, err := f.read(b2)
    check(err)
    fmt.printf("%d bytes @ %d: %s\n", n2, o2, string(b2))

    // the `io` package provides some functions that may
    // be helpful for file reading. for example, reads
    // like the ones above can be more robustly
    // implemented with `readatleast`.
    o3, err := f.seek(6, 0)
    check(err)
    b3 := make([]byte, 2)
    n3, err := io.readatleast(f, b3, 2)
    check(err)
    fmt.printf("%d bytes @ %d: %s\n", n3, o3, string(b3))

    // there is no built-in rewind, but `seek(0, 0)`
    // accomplishes this.
    _, err = f.seek(0, 0)
    check(err)

    // the `bufio` package implements a buffered
    // reader that may be useful both for its efficiency
    // with many small reads and because of the additional
    // reading methods it provides.
    r4 := bufio.newreader(f)
    b4, err := r4.peek(5)
    check(err)
    fmt.printf("5 bytes: %s\n", string(b4))

    // close the file when you're done (usually this would
    // be scheduled immediately after `open`ing with
    // `defer`).
    f.close()

}

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

f:\worksp\golang>go run base64-encoding.go
ywjjmtizit8kkiyoksctpub+
abc123!?$*&()'-=@~

ywjjmtizit8kkiyoksctpub-
abc123!?$*&()'-=@~

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