Go (golang) Tutorials – Buffered File I/O



Go (golang) Tutorials – Buffered File I/O

Go (golang) Tutorials - Buffered File I/O

#golang #go #input #output #file

File I/O – Buffered I/O
————————–
= Writing Data to File
= Reading from a File
= Appending to a File

bufwritedemo.go
—————-
package main
import (“os”
“bufio”
)
func main(){
file,err:=os.Create(“newfile”)
if err!=nil {
panic(err)
}
buf:=bufio.NewWriter(file) //Create a buffer for the os File
buf.WriteString(“Writing Data to Buffern”) //Write data to buffer
buf.Flush() //clears the buffer data and writes to the file
file.Close()
}

bufreaddemo.go
—————
package main
import (“os”
“bufio”
“fmt”
)
func main(){
file,_:=os.Open(“newfile”)
reader:=bufio.NewReader(file)
data,_:=reader.Peek(50)
fmt.Println(string(data))
file.Close()
}

appenddemo.go
————–
package main
import “os”
func main(){
//Opens an existing file with APPEND mode and Read/Write permission
file,err:=os.OpenFile(“newfile”,os.O_APPEND|os.O_WRONLY,0644)
if err !=nil {
panic(err)
}
file.WriteString(“Trying to appendn”)
file.Close()
}

Comments are closed.