How to update content of a text file?
In below example first character of a text file updated using WriteAt function which writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any.
"Po" has been updated by "Go" in below example.
Example
package main
import (
"io/ioutil"
"log"
"fmt"
"os"
)
func Beginning() {
// Read Write Mode
file, err := os.OpenFile("test.txt", os.O_RDWR, 0644)
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
defer file.Close()
len, err := file.WriteAt([]byte{'G'}, 0) // Write at 0 beginning
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
fmt.Printf("\nLength: %d bytes", len)
fmt.Printf("\nFile Name: %s", file.Name())
}
func ReadFile() {
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Panicf("failed reading data from file: %s", err)
}
fmt.Printf("\nFile Content: %s", data)
}
func main() {
fmt.Printf("\n######## Read file #########\n")
ReadFile()
fmt.Printf("\n\n######## WriteAt #########\n")
Beginning()
fmt.Printf("\n\n######## Read file #########\n")
ReadFile()
}
Output
######## Read file #########
File Content: Po Programming Language
######## WriteAt #########
Length: 1 bytes
File Name: test.txt
######## Read file #########
File Content: Go Programming Language
Most Helpful This Week
Create and Print Multi Dimensional Slice in Golang
How to check pointer or interface is nil?
How to handle HTTP Get response?
How to check UPPERCASE characters in a string in Golang?
How to compare equality of struct, slice and map?
Example of Sscan vs Sscanf vs Sscanln from FMT Package
Regular Expression to get a string between parentheses in Golang
How to reads and decodes JSON values from an input stream?
Golang Functions Returning Multiple Values
How to find length of Map in Go?