Writing to file using buffered writer
package main
import (
"bufio"
"log"
"os"
)
func main() {
/* Create and Open file for writing */
filefd, err := os.Create("blog.txt")
if err != nil {
log.Fatal(err)
}
defer filefd.Close()
/* create buffered write handler for opened file */
bufWriteHandle := bufio.NewWriter(filefd)
/* Write bytes to buffer */
byteData := []byte{'a', 'b', 'c', 'd', 'e', '\n'}
nn, err := bufWriteHandle.Write(byteData)
if err != nil {
log.Fatal(err)
}
log.Println("Number of bytes Written to buffer", nn)
/* Write String to buffer */
nn, err = bufWriteHandle.WriteString("String written using bufferd io\n")
log.Println("Number of bytes Written to buffer", nn)
/* flush from buffer to disk */
bufWriteHandle.Flush()
}
package main
import (
"log"
"os"
"bufio"
"fmt"
)
func main() {
/* Open existing file for reading */
filefd, err := os.Open("blog.txt")
if err != nil {
log.Fatal(err)
}
defer filefd.Close()
/* Create buffered read handler for opened file */
bufReadHandle := bufio.NewReader(filefd)
/* allocate slice of bytes to read */
readBytes := make([]byte, 64)
/* Read bytes and move pointer */
nn, err := bufReadHandle.Read(readBytes)
if err != nil {
log.Fatal(err)
}
fmt.Println("Number of bytes read", nn)
fmt.Println("Read Bytes:", string(readBytes))
}
No comments:
Post a Comment