Go copyFile()

1 개요[ | ]

Go copy()
package main

import (
	"fmt"
	"io/ioutil"
)

func copyFile(src, dst string) error {
	input, err := ioutil.ReadFile(src)
	if err != nil {
		return fmt.Errorf("error on ReadFile: %w", err)
	}
	err = ioutil.WriteFile(dst, input, 0644)
	if err != nil {
		return fmt.Errorf("error on WriteFile: %w", err)
	}
	return nil
}

func main() {
	err := copyFile("/etc/hosts", "/tmp/hosts.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("ok")
}
package main

import (
	"fmt"
	"io"
	"os"
)

func copyFile(src, dst string) error {
	source, err := os.Open(src)
	if err != nil {
		return fmt.Errorf("error on Open: %w", err)
	}
	defer source.Close()
	destination, err := os.Create(dst)
	if err != nil {
		return fmt.Errorf("error on Create: %w", err)
	}
	defer destination.Close()
	_, err = io.Copy(destination, source)
	if err != nil {
		return fmt.Errorf("error on Copy: %w", err)
	}
	return nil
}

func main() {
	err := copyFile("/etc/hosts", "/tmp/hosts.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("ok")
}

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}