On Sun, Jun 25, 2017 at 2:19 PM, Farid Shahy <fsh...@gmail.com> wrote: > > I have opened two files and want to use io.Copy to read from one file and > write to another, but it does not work. > If I close first file and then reopen it io.Copy will work correctly.Can > anybody please help on this issue? > >> f1, err := os.Create("File1.txt") >> checkErr(err, "Error creating File1.txt") >> // defer f1.Close() >> >> f2, err := os.Create("File2.txt") >> checkErr(err, "Error creating File2.txt") >> defer f2.Close() >> >> c1, err := f1.WriteString("Hello Pipe!") >> checkErr(err, "Error writting to File1.txt") >> fmt.Println("Written Count - f1: ", c1) >> >> err = f1.Sync() >> checkErr(err, "Error writting File1.txt to disk.") >> >> // f1.Close() >> // f1, err = os.OpenFile("File1.txt", os.O_RDWR, 0664) >> // defer f1.Close() >> // checkErr(err, "Error opening File1.txt again.") >> >> c2, err := io.Copy(f2, f1) >> checkErr(err, "Error copying File1txt to File2.txt.") >> fmt.Println("Written Count - f2: ", c2)
You need to reset the file position of f1 back to the start, using the Seek method. (By the way, you don't need to call Sync.) Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.