doudeng2184 2018-05-03 08:56
浏览 10
已采纳

文件字节数组长度转到

I have recently started to learn Go. To start with I decided that I would write some code to open a file and output its contents on the terminal window. So far I have been writing code like this:

file, err := os.Open("./blah.txt")

data := make([]byte, 100)

count, err := file.Read(data)

To obtain up to 100 bytes from a file. Is there any way to ascertain the byte count on a file, such that you could set the correct (or more sensible) byte array length just using the standard Go library?

I understand you could use a slice with something like Append() once the extremities of the array have been reached, but I just wondered whether the file size/length/whatever could be accessed prior to instantiating an array through file metadata or something similar.

  • 写回答

2条回答 默认 最新

  • doukuang1950 2018-05-03 09:00
    关注

    I assume what you need is a way to get file size in bytes to create a slice of the same size:

    f, err := f.Stat()
    // handle error 
    // ...
    size := f.Size()
    

    (see FileInfo for more)

    You can then use this size to initialise a slice.

    data := make([]byte, size)
    

    You can also consider reading the whole file in one call using ioutil.ReadFile.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探