droos02800 2017-02-12 20:06
浏览 226
已采纳

有效地从文件中读取前两个字节-Golang

I'm trying to find a good way of reading the first two bytes from a file using Go.

I have some .zip files in my current directory, mixed in with other files.

I would like to loop through all the files in the directory and check if the first two bytes contain the right .zip identifier, namely 50 4B.

What would be a good way to accomplish this using the standard library without having to read the entire file?

Going through the available functions in the io package I managed to find:

func LimitReader(r Reader, n int64) Reader

Which seems to fit my description, it reads from Reader (How do I get a Reader?) but stops after n bytes. Since I'm rather new to Go, I'm not sure how to go about it.

  • 写回答

1条回答 默认 最新

  • dongqiang5932 2017-02-12 20:19
    关注

    You get the initial reader by opening the file. For 2 bytes, I wouldn't use the LimitReader though. Just reading 2 bytes with io.ReadFull is easier.

    r, err := os.Open(file)
    if err != nil {
        return err
    }
    
    defer r.Close()
    
    var header [2]byte
    n, err := io.ReadFull(r, header[:])
    if err != nil {
        return err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog