How to Sync() a file?

95 views
Skip to first unread message

Farid Shahy

unread,
Jun 25, 2017, 5:20:53 PM6/25/17
to golang-nuts
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

Ian Lance Taylor

unread,
Jun 25, 2017, 5:38:57 PM6/25/17
to Farid Shahy, golang-nuts
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

Nathan Kerr

unread,
Jun 25, 2017, 5:39:56 PM6/25/17
to golang-nuts
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. For example: f1.Seek(0,0).

Farid Shahy

unread,
Jun 25, 2017, 5:53:44 PM6/25/17
to golang-nuts
Thanks it works using Seek(0, 0) without calling Sync().
Reply all
Reply to author
Forward
0 new messages