Golang : Reset or rewind io.Reader or io.Writer
Problem :
You have read file with io.Reader till EOF. Or you want to rewrite a file with io.Writer again.
How to reset or rewind the io.Reader or io.Writer?
Solution :
Looks like you are reading/accessing or writing in the file in sequential mode instead of random access mode.
Use os.File.Seek()
function to reset. Think of... like you are rewind a video or cassette tape with your finger or pencil.
For example :
imgfile, err := os.Open("./img.jpg")
if err != nil {
fmt.Println("img.jpg file not found!")
os.Exit(1)
}
defer imgfile.Close()
....
read file
....
imgfile.Seek(0, 0) // reset/rewind back to offset and whence 0 0
....
read file again
References :
http://golang.org/pkg/io/#Writer
See also : Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.1k Golang : calculate elapsed run time
+8.2k Golang : How to get garbage collection data?
+12.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+4.5k Golang : If else example and common mistake
+11.4k Elastic Search : Return all records (higher than default 10)
+12.1k Golang : Image to ASCII art example
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+22.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+12.6k Golang : How to check if a file is hidden?
+22.8k Golang : How to validate URL the right way
+4.9k Golang : Measure execution time for a function
+4.6k Unix/Linux : How to find out the hard disk size?