filmov
tv
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
-----------
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()
}
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()
}
Комментарии