gpt4 book ai didi

go - 为什么 f1.Read(buf) 没有读出内容到 buf?

转载 作者:数据小太阳 更新时间:2023-10-29 03:23:21 25 4
gpt4 key购买 nike

package main

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

func main() {

f1,_ := os.Create("f1")

io.WriteString(f1, "some content")

buf := make([]byte, 8)

f1.Read(buf)

fmt.Println(buf)

}

我创建一个文件,然后写入一些字符串。然后读出来,但是没有内容。

输出是:

go run test.go
[0 0 0 0 0 0 0 0]

最佳答案

在 Go 中,不要忽略错误。写入和读取文件时,请跟踪当前文件偏移量。

写入后偏移量位于文件末尾,您需要在读取前将偏移量设置为文件开头。例如,带有诊断信息,

package main

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

func main() {
f1, err := os.Create("f1")
if err != nil {
fmt.Println(err)
return
}
defer f1.Close()
// The file offset is its current location.
s, err := f1.Seek(0, io.SeekCurrent)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)
// writing takes place at the file offset, and
// the file offset is incremented by the number of bytes actually
// written.
n, err := f1.WriteString("some content")
fmt.Println("write: ", n, err)
if err != nil {
fmt.Println(n, err)
return
}
// The file offset is its current location
s, err = f1.Seek(0, io.SeekCurrent)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)

buf := make([]byte, 8)

// the read operation commences at the
// file offset, and the file offset is incremented by the number of
// bytes read. If the file offset is at or past the end of file, no
// bytes are read, and read() returns zero.
n, err = f1.Read(buf[:cap(buf)])
fmt.Println("read: ", n, err)
buf = buf[:n]
fmt.Println("buffer:", len(buf), buf)
if err != nil {
if err != io.EOF {
fmt.Println(n, err)
return
}
}

// The file offset is set to the start-of-file.
s, err = f1.Seek(0, io.SeekStart)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)
// the read operation commences at the
// file offset, and the file offset is incremented by the number of
// bytes read. If the file offset is at or past the end of file, no
// bytes are read, and read() returns zero.
n, err = f1.Read(buf[:cap(buf)])
fmt.Println("read: ", n, err)
buf = buf[:n]
fmt.Println("buffer:", len(buf), buf)
if err != nil {
if err != io.EOF {
fmt.Println(n, err)
return
}
}
}

Playground :https://play.golang.org/p/hPUn1ltKP2t

输出:

offset: 0
write: 12 <nil>
offset: 12
read: 0 EOF
buffer: 0 []
offset: 0
read: 8 <nil>
buffer: 8 [115 111 109 101 32 99 111 110]

关于go - 为什么 f1.Read(buf) 没有读出内容到 buf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49095867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com