Go (golang) Tutorials – File I/O using OS Package



Go (golang) Tutorials – File I/O using OS Package

Go (golang) Tutorials - File I/O using OS Package

#golang #go #input #output #file

File I/O – OS Package
———-
= Writing a []byte to a file
= Writing a string to a file
= Read []byte from a file
= Seek
= Read a set of bytes from a file

filedemo.go
———–
package main
import “os”
func main(){
file,err:=os.Create(“myfile”) //Create a new file myfile
if err!=nil {
panic(err)
}
data:=[]byte(“Hello worldn”)
file.Write(data) //Data as a byte array
file.WriteString(“This is a Stringn”) //Write data as a string
file.Close()
}

readdemo.go
———–
package main
import ( “fmt”
“os”
)
func main(){
file,err:=os.Open(“myfile”)
if err!=nil {
panic(err)
}
data:=make([]byte,5) //The data read from the file will be of the size of the byte array
file.Seek(6,0) //I want to seek the file pointer to the 5th byte of the data
//Seek has two arguments, first one is the position of file pointer to read data
//From where in the file to read from, 0 – beginning, 1-at current position, 2-from end

file.Read(data) //read the data from file to the byte array ‘data’
//fmt.Printf(“The file data is %sn”,string(data))
fmt.Println(string(data))
file.Seek(0,0)
newdata:=make([]byte,5)
file.Read(newdata)
fmt.Println(string(newdata))
file.Close()
}

Comments are closed.