#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 world\n")
file.Write(data) //Data as a byte array
file.WriteString("This is a String\n") //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 %s\n",string(data))
fmt.Println(string(data))
file.Seek(0,0)
newdata:=make([]byte,5)
file.Read(newdata)
fmt.Println(string(newdata))
file.Close()
}
Watch video Go (golang) Tutorials - File I/O using OS Package online, duration hours minute second in high quality that is uploaded to the channel Ambasoft Java 05 April 2018. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 10,126 times and liked it 120 visitors.