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

1번째 줄: 1번째 줄:
==개요==
==개요==
;Go copy()
;Go copy()
<syntaxhighlight lang='go run'>
package main
import (
"fmt"
"io/ioutil"
)
func copy(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 := copy("/etc/hosts", "/tmp/hosts.txt")
if err != nil {
panic(err)
}
fmt.Println("ok")
}
</syntaxhighlight>


<syntaxhighlight lang='go' run>
<syntaxhighlight lang='go' run>

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

1 개요

Go copy()
package main

import (
	"fmt"
	"io/ioutil"
)

func copy(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 := copy("/etc/hosts", "/tmp/hosts.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("ok")
}
package main

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

func copy(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 := copy("/etc/hosts", "/tmp/hosts.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("ok")
}

2 같이 보기

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