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

(새 문서: ==개요== ;Go copy() ==같이 보기== * 함수 copy() 분류: Go)
 
 
(같은 사용자의 중간 판 9개는 보이지 않습니다)
1번째 줄: 1번째 줄:
==개요==
==개요==
;Go copy()
;Go copy()
<syntaxhighlight lang='go' run>
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")
}
</syntaxhighlight>
<syntaxhighlight lang='go' run>
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")
}
</syntaxhighlight>


==같이 보기==
==같이 보기==
* [[Go Mkdir()]]
* [[Go ReadAllText()‎]]
* [[함수 copy()]]
* [[함수 copy()]]


[[분류: Go]]
[[분류: Go]]

2023년 4월 13일 (목) 10:45 기준 최신판

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