In this example we are going to see some very basic file operations with Golang. It includes, reading, writing and truncating. It will either be an individual or combined operation.


Files


file-1.txt


1
2
3

4
5
6

file-3.txt


a
b
c

file-4.txt


2021-12-18T11:17:14Z

main.go


package main

import (
"fmt"
"log"

"github.com/you/client/file"
)

func main() {
lines, err := file.ReadContentLineByLineIntoSlice("./file-1.txt")
if err != nil {
log.Fatalln(err)
}
fmt.Println(lines)

err = file.CreateAndWriteContent("./file-2.txt")
if err != nil {
log.Fatalln(err)
}

err = file.OpenReadAndAppendContent("./file-3.txt")
if err != nil {
log.Fatalln(err)
}

err = file.OpenReadAndReplaceContent("./file-4.txt")
if err != nil {
log.Fatalln(err)
}
}

file.go


package file

import (
"bufio"
"fmt"
"os"
"time"
)

// Open a file for read only and read line by line into a slice.
func ReadContentLineByLineIntoSlice(path string) ([]string, error) {
var lines []string

file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() != "" {
lines = append(lines, scanner.Text())
}
}
if err := scanner.Err(); err != nil {
return nil, err
}

return lines, nil
}

// Create a file if it does not exists, open for write only and write to it.
// It replaces the content if the file was already existed and full.
func CreateAndWriteContent(path string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer file.Close()

writer := bufio.NewWriter(file)
for i := 0; i <= 5; i++ {
// Version 1
// if _, err := writer.WriteString(fmt.Sprintf("%d\n", i)); err != nil {
// return err
// }

// Version 2
if _, err := fmt.Fprintf(writer, "%d\n", i); err != nil {
return err
}
}
if err := writer.Flush(); err != nil {
return err
}

return nil
}

// Open an existing file to read it first and append the content at the end.
func OpenReadAndAppendContent(path string) error {
file, err := os.OpenFile(path, os.O_RDWR, 0600)
if err != nil {
return err
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() != "" {
fmt.Println(scanner.Text())
}
}
if err := scanner.Err(); err != nil {
return err
}

if _, err := fmt.Fprintf(file, "last\n"); err != nil {
return err
}

return nil
}

// Open an existing file to read it first and replace the content.
func OpenReadAndReplaceContent(path string) error {
file, err := os.OpenFile(path, os.O_RDWR, 0600)
if err != nil {
return err
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
if scanner.Text() != "" {
fmt.Println(scanner.Text())
}
}
if err := scanner.Err(); err != nil {
return err
}

if err := file.Truncate(0); err != nil {
return err
}
if _, err := file.Seek(0, 0); err != nil {
return err
}
if _, err := fmt.Fprint(file, time.Now().Format(time.RFC3339)); err != nil {
return err
}

return nil
}