본문 바로가기
Go

[Go] File handling

by llHoYall 2020. 12. 2.

File Creating

file, err := os.Open(filename)
if err != nil {
  log.Fatal(err)
}

File Reading

scanner := bufio.NewScanner(file)
for scanner.Scan() {
  fmt.Println(scanner.Text())
}

Scan() method reads one line from the file.

Text() method returns the content of the line as a string.

File Closing

err = file.Close()
if err != nil {
  log.Fatal(err)
}

Example

package main

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

func main() {
  file, err := os.Open("../README.md")
  if err != nil {
    log.Fatal(err)
  }
  
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    fmt.Println(scanner.Text())
  }
  
  err = file.Close()
  if err != nil {
    log.Fatal(err)
  }
  
  if scanner.Err() != nil {
    log.Fatal(scanner.Err())
  }
}

Err() method indicates whether an error occurred while reading the contents of the file.

'Go' 카테고리의 다른 글

[Go] The Error of Floating Point Number  (0) 2021.10.04
[Go] Operator  (0) 2021.10.04
[Go] Configure VSCode  (0) 2020.11.28
[Go] User-Defined Type  (0) 2020.11.02
[Go] Basic  (0) 2020.10.26

댓글