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

preview_player
Показать описание
#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

-----------
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()
}

-----------
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()
}
Рекомендации по теме
Комментарии
Автор

nice easy tutorial, i like how you focus one 1 part at a time keeping the videos nice and short!

bryku
Автор

Thanks for this useful content
Do you have a plan to cover this language and provide content around it?

baxiry.
Автор

I want read multiple xml files in a path which matches the pattern.Can you please say how to do that? If there are any video related to this please share the link

ravichandrak