go读取文件内容写入另一文件中
go读取文件内容写入另一文件中
package main import ( "fmt" "os" "io" ) func read()(c string){ //读取文件 f := "C:\\Users\\Administrator\\Desktop\\go\\1.txt" file, _ := os.Open(f) defer file.Close() var buf [128]byte // 记录一次读取的量 var content []byte // 定义切片,整体的数据量 for { n, err := file.Read(buf[:]) // 根据 if err == io.EOF { // 读取结束 fmt.Println("read end") break } if err != nil { fmt.Println("read file err ", err) return } //向切片追加新元素 content = append(content, buf[:n]...) } // fmt.Println(content) c = string(content) return } func write(content string){ writeFile := "C:\\Users\\Administrator\\Desktop\\go\\write.txt" fileto, _ := os.OpenFile(writeFile, os.O_WRONLY, 0666) defer fileto.Close() res,error :=fileto.WriteString(string(content)) if error != nil { fmt.Println("write file err ", error) return } if res == 1002 { fmt.Println("write success") return } } func main(){ var c string =read() write(c) }