Go readAllText()

(Go ReadAllText()에서 넘어옴)

1 개요[ | ]

Go readAllText()
package main

import (
	"fmt"
	"os"
)

func main() {
	fileBytes, err := os.ReadFile("/etc/hosts")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(fileBytes))
}
package main

import (
	"fmt"
	"os"
)

func readAllText(filepath string) (text string, err error) {
	fileBytes, err := os.ReadFile(filepath)
	if err != nil {
		return "", fmt.Errorf("error on ReadFile: %w", err)
	}
	return string(fileBytes), nil
}

func main() {
	text, err := readAllText("/etc/hosts")
	if err != nil {
		panic(err)
	}
	fmt.Println(text)
}
package main

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

func readAllText(filepath string) (text string, err error) {
	buf := bytes.NewBuffer(nil)
	f, err := os.Open(filepath)
	if err != nil {
		return "", fmt.Errorf("error on Open: %w", err)
	}
	defer f.Close()
	_, err = io.Copy(buf, f)
	if err != nil {
		return "", fmt.Errorf("error on Copy: %w", err)
	}
	return buf.String(), nil
}

func main() {
	text, err := readAllText("/etc/hosts")
	if err != nil {
		panic(err)
	}
	fmt.Println(text)
}

2 같이 보기[ | ]

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