I assume that you mean by io.Copy not working correctly is that you expect the entire contents of File1.txt to be in File2.txt.
This does not happen in your code (without reopening f1) because Files maintain an offset inside the file that remembers where the next operation should take place. After calling f1.WriteString the offset is no longer at the beginning of the file, it is at the end of the written string. To go to the beginning of the file, use File.Seek <https://godoc.org/os#File.Seek>. For example: f1.Seek(0,0). On Sunday, June 25, 2017 at 11:20:53 PM UTC+2, Farid Shahy wrote: > > Hi > 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) >> > > Thanks > Farid Shahy > -- 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.