Created
June 10, 2021 12:35
-
-
Save sazid/58dca633fad53231df17c2db9e8ed354 to your computer and use it in GitHub Desktop.
Demonstration of file seek handle in Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"io/ioutil" | |
"os" | |
"strings" | |
) | |
func GetFile() *os.File { | |
// Create a temporary file. | |
file, _ := ioutil.TempFile("", "my_temp_file_*") | |
// Write something, | |
file.WriteString("Hello World") | |
// Sync/flush in-memory content to disk. | |
file.Sync() | |
return file | |
} | |
func main() { | |
f := GetFile() | |
defer os.Remove(f.Name()) | |
// If you try to read anything from this file now, | |
// you'll get empty result! | |
buf := new(strings.Builder) | |
io.Copy(buf, f) | |
fmt.Println(buf.String()) // output: "" | |
// Reason: the seek handle (pointer to the current | |
// cursor position) has changed and now pointing | |
// to the end of the file after writing the | |
// previous content. (imagine the cursor position | |
// when you type on a keyboard). | |
// Fix: simply move the seek handle back to the | |
// starting position. | |
f.Seek(0, 0) | |
buf = new(strings.Builder) | |
io.Copy(buf, f) | |
fmt.Println(buf.String()) // output: "Hello World" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment