Write Files
Writing a file using a struct and encoding data in JSON:
import (
"encoding/json"
"os"
)
type Data struct {
Field1 string
Field2 int
// Add more fields as needed
}
// Example of writing data to file using JSON encoding
func writeToJSONFile(filename string, data Data) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
if err := encoder.Encode(data); err != nil {
return err
}
return nil
}Writing byte slices using
os.Createandf.Write:
Writing strings using
f.WriteString():
Using
bufioto write data to a file:
Using
bufioto write line by line:
Example usage:
Last updated
Was this helpful?