Go File Operator

Read File

Read content from a file, string, or bytes are very important for any program language. In this article, we have showed the following package to read file:

  • os
  • ioutil

If you want to read from buffer, you can use bufio to read file or string. At the same time you also can use strings, bytes to read string and []byte

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func ReadString(s string) {
	reader := strings.NewReader(s)
	bytes := make([]byte, 50)
	for {
		n, err := reader.Read(bytes)
		if err != nil {
			break
		} else {
			fmt.Println(string(bytes[:n]))
		}
	}
}

func ReadBytes(b []byte) {
	reader := bytes.NewReader(b)
	bytes := make([]byte, 50)
	for {
		n, err := reader.Read(bytes)
		if err != nil {
			break
		} else {
			fmt.Println(string(bytes[:n]))
		}
	}
}

func ReadFileWithBuffer(filename string) error {
	f, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}

	reader := bufio.NewReader(f)
	bytes := make([]byte, 50)
	for {
		n, err := reader.Read(bytes)
		if err != nil {
			break
		} else {
			fmt.Println(string(bytes[:n]))
		}
	}
	return nil
}

func ReadFile(filename string) error {
	data, err := os.ReadFile(filename)
	if err != nil {
		return err
	}
	fmt.Println(string(data))
	return nil
}

func ReadFileWithioutil(filename string) error {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}

	fmt.Println(string(data))
	return nil
}

func main() {
	file := "./temp.txt"

	err := ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}

	err = ReadFileWithioutil(file)

	if err != nil {
		log.Fatal(err)
	}

	err = ReadFileWithBuffer(file)
	if err != nil {
		log.Fatal(err)
	}

	data, err := os.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}

	ReadBytes(data)
	ReadString(string(data))
}

File Exists

In this code, we will use os.Stat to get the file properties, and then check the error type

package main

import (
	"errors"
	"fmt"
	"os"
)

func file_exists(path string) bool {
	_, err := os.Stat(path)
	return errors.Is(err, os.ErrNotExist)
}

func main() {
	fmt.Println(file_exists("./main.go"))
	fmt.Println(file_exists("./main1.go"))
}

Walk Dir

  • Here is the method to go walk all the dir with deep iteration
func walk_dir(path string) {
	dirInf, err := os.Stat(path)

	if errors.Is(err, os.ErrNotExist) {
		panic(err)
	}

	if !dirInf.IsDir() {
		fmt.Println(dirInf.Name())
		return
	}

	dir_entires, err := os.ReadDir(path)
	if err != nil {
		panic(err)
	}

	for _, dir := range dir_entires {
		walk_dir(filepath.Join(path, dir.Name()))
	}
}
  • Walk dir with WalkFunc
    • WalkDir function
    package main
    
    import (
        "errors"
        "io/fs"
        "log"
        "os"
        "path/filepath"
    )
    
    func walk_dir(path string) {
        dirInf, err := os.Stat(path)
    
        if errors.Is(err, os.ErrNotExist) {
            panic(err)
        }
    
        if !dirInf.IsDir() {
            log.Printf("This is a file not a dir %s\n", filepath.Join(path, dirInf.Name()))
            return
        }
    
        filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error {
            if err != nil {
                return err
            }
            if !d.IsDir() {
                log.Printf("%s\n", path)
            }
            return nil
        })
    }
    
    func main() {
        walk_dir("../..")
    }
    
    • Walk function
    package main
    
    import (
        "errors"
        "io/fs"
        "log"
        "os"
        "path/filepath"
    )
    
    func walk_dir(path string) {
        dirInf, err := os.Stat(path)
    
        if errors.Is(err, os.ErrNotExist) {
            panic(err)
        }
    
        if !dirInf.IsDir() {
            log.Printf("This is a file not a dir %s\n", filepath.Join(path, dirInf.Name()))
            return
        }
    
        filepath.Walk(path, func(path string, d fs.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if !d.IsDir() {
                log.Printf("%s\n", path)
            }
            return nil
        })
    }
    
    func main() {
        walk_dir("../")
    }
    

Copy File

package main

import (
	"io"
	"io/ioutil"
	"log"
	"os"
)

func CopyFileOnceRead(source, dest string) error {
	data, err := ioutil.ReadFile(source)
	if err != nil {
		return err
	}

	writer, err := os.OpenFile(dest, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
	if err != nil {
		return err
	}

	_, err = writer.Write(data)

	return err
}

func CopyFileWithStream(source, dest string) error {
	reader, err := os.Open(source)
	if err != nil {
		return err
	}

	writer, err := os.OpenFile(dest, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
	if err != nil {
		return err
	}

	_, err = io.Copy(writer, reader)

	return err
}

func CopyFileWithStreamBuf(source, dest string) error {
	reader, err := os.Open(source)
	if err != nil {
		return err
	}

	writer, err := os.OpenFile(dest, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0755)
	if err != nil {
		return err
	}

	var buf [2048]byte

	_, err = io.CopyBuffer(writer, reader, buf[:])

	return err
}

func main() {
	// err := CopyFileOnceRead("./main.go", "./main1.go")
	// if err != nil {
	// 	log.Fatalln(err)
	// }

	err := os.Remove("./main1.go")
	if err != nil {
		log.Println(err)
	}

	CopyFileWithStreamBuf("./main.go", "./main1.go")
}

Rename file

package main

import (
	"log"
	"os"
)

func main() {
	err := os.Rename("./main1.go", "./main2.go")
	if err != nil {
		log.Fatalln(err)
	}
}
Built with Hugo
Theme Stack designed by Jimmy