io.Copy在os.File类型之间不复制数据。

huangapple go评论92阅读模式
英文:

io.Copy is not copying data between os.File types

问题

我正在使用os.Create函数从代码中创建2个文件。

我正在向file1写入一些字符串,然后尝试使用io.Copy将file1的内容复制到file2,但它不起作用。

没有抛出任何错误。有人可以告诉我这里发生了什么吗?谢谢。

Playground链接- https://play.golang.org/p/lv_2VfsNIfI

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
)

func main() {

	file1, err := os.Create("file1")
	if err != nil {
		log.Fatal(err)
	}
	file1.WriteString("Some test data")
	defer file1.Close()
	defer os.Remove(file1.Name())

	log.Println("File1 Data : ", readFile(file1.Name()))

	file2, err := os.Create("file2")
	if err != nil {
		log.Fatal(err)
	}
	defer file2.Close()
	defer os.Remove(file2.Name())

	w, err := io.Copy(file2, file1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Copied", w)

	log.Println("File2 Data : ", readFile(file2.Name()))
}

func readFile(fname string) string {
	data, err := ioutil.ReadFile(fname)
	if err != nil {
		log.Fatal(err)
	}

	return string(data)
}

我得到的输出是:

2009/11/10 23:00:00 File1 Data :  Some test data
2009/11/10 23:00:00 Copied 0
2009/11/10 23:00:00 File2 Data :
英文:

I am creating 2 files from code using os.Create function.

I am writing some string to file1 and then trying to copy the content of file1 to file2 using io.Copy but its not working.

There are no errors thrown. Can anyone tell me what is happening here ? Thanks.

Playground Link - https://play.golang.org/p/lv_2VfsNIfI

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
)

func main() {

	file1, err := os.Create("file1")
	if err != nil {
		log.Fatal(err)
	}
	file1.WriteString("Some test data")
	defer file1.Close()
	defer os.Remove(file1.Name())

	log.Println("File1 Data : ", readFile(file1.Name()))

	file2, err := os.Create("file2")
	if err != nil {
		log.Fatal(err)
	}
	defer file2.Close()
	defer os.Remove(file2.Name())

	w, err := io.Copy(file2, file1)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Copied", w)

	log.Println("File2 Data : ", readFile(file2.Name()))
}

func readFile(fname string) string {
	data, err := ioutil.ReadFile(fname)
	if err != nil {
		log.Fatal(err)
	}

	return string(data)
}

Output I am getting,

2009/11/10 23:00:00 File1 Data :  Some test data
2009/11/10 23:00:00 Copied 0
2009/11/10 23:00:00 File2 Data : 

答案1

得分: 2

你需要使用file1.Seek(0,0)将文件1的指针回到开头,因为你的文件指针在写入数据的末尾。

...
file1.WriteString("一些测试数据")
file1.Seek(0,0)
defer file1.Close()
...
英文:

You need to seek back to the beginning of file1 using file1.Seek(0,0) because your file cursor is at the end of the written data.

...
file1.WriteString("Some test data")
file1.Seek(0,0)
defer file1.Close()
...

huangapple
  • 本文由 发表于 2021年9月6日 02:00:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69065978.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定