GolangSnippet
Last updated at 2023-08-21

Quick Golang Files Tutorial for Beginner

ClickUp
Note
AI Status
Last Edit By
Last edited time
Aug 21, 2023 09:28 AM
Metatag
Slug
golang-files-tutorial-beginner
Writer
Published
Published
Date
Aug 21, 2023
Category
Golang
Snippet
Golang is one of the best programming languages created by Google. It is so popular that it has 100K+ stars on Github and 50K+ commits. There are 2000 contributors, as shown in the public repository.
This article will guide you through working with files in Golang.
Working with files is one of the most common programming tasks. It's because files are an important part of programming, whether high-level or low-level.
You will use Go version 1.18 in this article. There are packages that make working with files easier in Golang. You will use os, ioutil, and fmt packages in this guide.
To make learning easier, you will learn using the waterfall approach. By using waterfall, you will basically learn Golang files functions like if you find the use case in your own project.
This example will use the use case of a program that handles user information stored in the user_info.txt file.

Checking If a File Exists

Suppose you need to check whether user information exists in a directory. You can use this sample code to check whether user_info.txt exists.
package main import ( "errors" "fmt" "os" ) func main() { _, err := os.Stat("user_info.txt") if errors.Is(err, os.ErrNotExist) { fmt.Println("User info file does not exist") } else { fmt.Println("User info file is exists") } }

Creating Files

When you don’t find user_info.txt you need to create it.
Creating files is straightforward using the os.Create function:
package main import ( "fmt" "log" "os" ) func main() { file, err := os.Create("user_info.txt") defer file.Close() if err != nil { log.Fatal(err) } fmt.Println("User info file created") }

Deleting Files

If the user wants to remove their data for a certain purpose, you can use the os.Remove function:
package main import ( "fmt" "log" "os" ) func main() { err := os.Remove("user_info.txt") if err != nil { log.Fatal(err) } fmt.Println("User info file deleted") }

Getting File Size

You need to check the user_info.txt file size because users need the data to decide whether to export the data to another file.
You can use the os.Stat returned object and invoke .Size() method.
package main import ( "fmt" "log" "os" ) func main() { fileInfo, err := os.Stat("user_info.txt") if err != nil { log.Fatal(err) } fileSize := fileInfo.Size() fmt.Printf("User info file size: %d bytes\\n", fileSize) }

Obtaining Last Modification Time

To ensure that users always update their information, you need to display the last modification time.
This feature helps users notice when they don’t make an update for a long time.
You can still use the os.Stat returned object. This time you use .ModTime() method.
package main import ( "fmt" "log" "os" ) func main() { fileName := "user_info.txt" fileInfo, err := os.Stat(fileName) if err != nil { log.Fatal(err) } modificationTime := fileInfo.ModTime() fmt.Println("Last modified:", modificationTime) }

Reading File Contents

Displaying user_info.txt can be done using ioutil.ReadFile function.
When user_info.txt becomes large, you can read the file line by line to save memory.
package main import ( "fmt" "io/ioutil" "log" ) func main() { content, err := ioutil.ReadFile("user_info.txt") if err != nil { log.Fatal(err) } fmt.Println(string(content)) }

Writing to Files

The user should input their basic information for identification purposes.
You can use the ioutil.WriteFile function to update the user_info.txt file.
package main import ( "fmt" "io/ioutil" "log" ) func main() { fileName := "user_info.txt" data := []byte("name: Jack\\nage: 34\\nhobby: Fishing\\n") err := ioutil.WriteFile(fileName, data, 0644) if err != nil { log.Fatal(err) } fmt.Println("Done writing") }

Appending to Files

When the user needs to update a job, you can perform append to write the job information to user_info.txt.
You can follow this example to update user_info.txt with new information.
package main import ( "log" "os" ) func main() { fileName := "user_info.txt" f, err := os.OpenFile( fileName, os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0644 ) if err != nil { log.Fatal(err) } defer f.Close() if _, err := f.WriteString("job: Software Engineer\\n"); err != nil { log.Fatal(err) } }

Copying Files

Creating a backup is as important as keeping the original one. In case something happened, the user never lost their data.
Copying files is simple with this code:
package main import ( "log" "io/ioutil" ) func main() { src := "user_info.txt" dest := "user_info2.txt" bytesRead, err := ioutil.ReadFile(src) if err != nil { log.Fatal(err) } err = ioutil.WriteFile(dest, bytesRead, 0644) if err != nil { log.Fatal(err) } }

Listing Files

As different users store the information in different files, when an admin needs to list the information of all the users, you need to show a list of user information.
To list files, you can use filepath.Walk to traverse directories:
package main import ( "path/filepath" "fmt" "os" "log" ) func main() { var files []string root := "/home/user/Documents" err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { fmt.Println(err) return nil } if !info.IsDir() && filepath.Ext(path) == ".txt" { files = append(files, path) } return nil }) if err != nil { log.Fatal(err) } for _, file := range files { fmt.Println(file) } }

Conclusion

File handling in Golang allows you to work with files easily by only using the ioutil, os, and fmt packages.
In this tutorial, you have learned how to utilize those packages to allow you to do Golang file operations on user_info.txt.
Happy file writing!

Discussion (0)

Related Posts