Recent Comments
Link
Recent Posts
Today
Total
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
관리 메뉴

Study Memory Work

[Go Lang] File IO : 파일 읽기 본문

Programing/Go

[Go Lang] File IO : 파일 읽기

Hera Choi 2023. 2. 28. 15:19

 

파일 읽기 Read

Open > file size 추출 > file.read

package main

import (
	"fmt"
	"os"
)

func errCheck1(e error) {
	if e != nil {
		panic(e)
	}
}

func errCheck2(e error) {
	if e != nil {
		fmt.Println(e)
		return
	}
}

func main() {
	// 파일 읽기 예제1
	file, err := os.Open("fileIO/test_read.txt")
	errCheck1(err)

	fileInfo, err := file.Stat() // 파일 정보들.
	errCheck2(err)

	fd1 := make([]byte, fileInfo.Size()) // 파일사이즈만큼의 byte 배결 생성
	ct1, err := file.Read(fd1)

	fmt.Println("파일 정보 출력(1) : ", fileInfo)
	fmt.Println("파일 이름(2) : ", fileInfo.Name())
	fmt.Println("파일 크기(3) : ", fileInfo.Size())
	fmt.Println("파일 수정 시간(4) : ", fileInfo.ModTime())
	fmt.Printf("읽기 작업 완료 (%d bytes)\n\n", ct1)
	//fmt.Println(fd1)
	fmt.Println(string(fd1))

	fmt.Println()

	defer file.Close()
}

 

파일읽기 : Seek, Offset

...

func main() {

	// 읽기 예제 2 ( 탐색: Seek(Offset) ) 커서 제어!!	-> 보다 전체를 가져와서 파싱하는 게 더 나음....!
	o1, err := file.Seek(20, 0) // 0: 처음위치, 1: 현재위치, 2: 끝, whernce 기준으로 offset 만큼 커서 이동
	/// o1 > 읽고난 후 현재 커서를 가지고 있음
	errCheck1(err)

	fd2 := make([]byte, 40)
	ct2, err := file.Read(fd2)
	errCheck1(err)
	fmt.Println(string(fd2))
	fmt.Printf("읽기 작업 완료 (%d bytes) (%d ret)\n\n", ct2, o1)

}
	// 읽기 예제 3
	o2, err := file.Seek(0, 0) // 커서를 처음으로 돌린다.
	errCheck1(err)
	fd3 := make([]byte, 50)
	ct3, err := file.ReadAt(fd3, 8) // 몇번째부터 가져올까?
	errCheck1(err)

	fmt.Println(string(fd3))
	fmt.Printf("읽기 작업 완료 (%d bytes) (%d ret)\n\n", ct3, o2)

 

ioutil Package 를 활용하여 파일 읽기

 

ioutil package - io/ioutil - Go Packages

TempFile creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random

pkg.go.dev

  • 더욱 편리하고 직관적으로 파일 읽기, 쓰기 가능
  • writeFile(), ReadFile(), ReadAll() 등 사용 가능
  • 파일 모드(chmod, chown, chgrp) 사용하여 파일 쓰기 가능
    • 읽기권한: 4, 쓰기권한: 2, 실행권한: 1
    • 소유자, 그룹, 기타 사용자 순서(644)
 

os package - os - Go Packages

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is availab

pkg.go.dev

  • sync()작업이나 close작업을 해줄 필요가 없음
package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func errCheck(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {

	s := "Hello Golang\n File Write Test!\n"
	err := ioutil.WriteFile("fileIO/test_write1.txt", []byte(s), os.FileMode(0644))
    															// 파일 권한 설정
	errCheck(err)

	data, err := ioutil.ReadFile("fileIO/test_write1.txt")
	errCheck(err)

	fmt.Println("=====================================")
	fmt.Println(string(data))
	fmt.Println("=====================================")

}

 

Bufio Package 를 이용한 파일 Read, Write

 

bufio package - bufio - Go Packages

The simplest use of a Scanner, to read standard input as a set of lines. package main import ( "bufio" "fmt" "os" ) func main() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) // Println will add back the final '\n'

pkg.go.dev

  • ioutil, bufio 등은 Io.Reader, io.Writer 인터페이스를 구현 함 -> 즉, writer, Read 메소드를 사용 가능
  • Buffer 
a -----> a
b -----> ab
c -----> abc
d -----> abcd
e -----> e ----->abcd
f -----> ef -----> abcd
g -----> efg -----> abcd
h -----> efgh -----> abcd
i -----> i -----> abcdefgh
...
package main

import (
	"bufio"
	"fmt"
	"os"
)

func errCheck1(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {

	file, err := os.OpenFile("fileIO/test_write2.txt", os.O_CREATE|os.O_RDWR, os.FileMode(0777))
	// 													없으면 create, 있으면 ReadWrite Mode로 Open
	errCheck1(err)
    
	wt := bufio.NewWriter(file) 	// writer 반환. (버퍼 사용)
	wt.WriteString("Hello Golang\n File Write Test!\n")		// 버퍼에 담기
	wt.Write([]byte("Hello Golang\n File Write Test!\n"))	// 버퍼에 담기

	fmt.Println("사용한 Buffer Size (%d bytes)", wt.Buffered())
	fmt.Println("남은 Buffer Size (%d bytes)", wt.Available())
	fmt.Println("전체 Buffer Size (%d bytes)", wt.Size())

	wt.Flush()		// 버퍼 비우고 파일 쓰기

	fmt.Println("=====================================")

	rt := bufio.NewReader(file)		// reader 반환
	fi, err := file.Stat()
	errCheck1(err)

	b := make([]byte, fi.Size())

	fmt.Println("파일 정보 출력 Name : ", fi.Name())
	fmt.Println("파일 정보 출력 Size : ", fi.Size())
	fmt.Println("파일 정보 출력 ModTime : ", fi.ModTime())
	fmt.Println("파일 정보 출력 : ", fi)

	file.Seek(0, os.SEEK_SET) // 커서 맨 앞으로 이동
	data, _ := rt.Read(b)

	fmt.Printf("전체 buffer size (%d bytes)]\n", rt.Size())
	fmt.Printf("읽기 작업 완료: (%d bytes)\n", data)
	fmt.Println("파일 내용 : \n", string(b))

}

'Programing > Go' 카테고리의 다른 글

[Go Lang] 구조체 - 선언, 활용  (0) 2023.03.02
[Go Lang] 사용자 정의 타입  (0) 2023.02.28
[Go Lang] File IO : 파일 쓰기  (0) 2023.02.27
[Go Lang] 에러처리  (0) 2023.02.27
[Go Land] Time  (0) 2023.02.23