"Go copyFile()"의 두 판 사이의 차이

잔글 (Jmnote님이 Go copyFille() 문서를 Go copyFile() 문서로 이동했습니다)
10번째 줄: 10번째 줄:
)
)


func copy(src, dst string) error {
func copyFile(src, dst string) error {
input, err := ioutil.ReadFile(src)
input, err := ioutil.ReadFile(src)
if err != nil {
if err != nil {
23번째 줄: 23번째 줄:


func main() {
func main() {
err := copy("/etc/hosts", "/tmp/hosts.txt")
err := copyFile("/etc/hosts", "/tmp/hosts.txt")
if err != nil {
if err != nil {
panic(err)
panic(err)
40번째 줄: 40번째 줄:
)
)


func copy(src, dst string) error {
func copyFile(src, dst string) error {
source, err := os.Open(src)
source, err := os.Open(src)
if err != nil {
if err != nil {
59번째 줄: 59번째 줄:


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

2023년 4월 13일 (목) 10:38 판

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 }}