golang文件读取-按指定BUFF大小读取

版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/79163803

golang文件读取-按指定BUFF大小读取

a.txt文件内容:

ABCDEFGHI
HELLO GOLANG

package main

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

func main() {
    fileName := "C:\\Robert\\日志分析\\tools_go\\vdn_sqlInterface\\a.txt"
    file, err := os.OpenFile(fileName, os.O_RDWR, 0666)
    if err != nil {
        fmt.Println("Open file error!", err)
        return
    }
    defer file.Close()

    stat, err := file.Stat()
    if err != nil {
        panic(err)
    }

    var size = stat.Size()
    fmt.Println("file size=", size)

    // define read block size = 2
    buf := make([]byte, 2)
    for {
        length, err := file.Read(buf)
        if err != nil {
            if err == io.EOF {
                break
            } else {
                fmt.Println("Read file error!", err)
                return
            }
        }

        fmt.Println(length, string(buf))
    }

    fmt.Println("File read ok!")
}

输出:
每次读取2个字节的大小并输出

file size= 23
2 AB
2 CD
2 EF
2 GH
2 I
2
H
2 EL
2 LO
2 G
2 OL
2 AN
1 GN
File read ok!

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页