Go os Package open()

Introduction

To open a file in Go, use the Open function from the os package.

Here is an example of how to read the contents of a file and display them on the terminal:

package main /*from  w  w w  . j av a2 s.c o  m*/

import ( 
    "fmt" 
    "os" 
) 

func main() { 
    file, err  := os.Open("main.go") 
    if err  != nil { 
        // handle the error here 
        return 
    } 
    defer file.Close() 

    // get the file size 
    stat, err  := file.Stat() 
    if err  != nil { 
        return 
    } 
    // read the file 
    bs  := make([]byte, stat.Size()) 
    _, err = file.Read(bs) 
    if err  != nil { 
        return 
    } 

    str  := string(bs) 
    fmt.Println(str) 
} 



PreviousNext

Related