This article explores file handling in Golang, covering libraries, path construction, metadata retrieval, and reading and writing files.
In this article, we explore file handling in Golang. File handling involves managing files by retrieving metadata, creating new files, and reading from or writing to files. Golang’s standard libraries integrate these capabilities, ensuring consistent behavior across different operating systems.
Golang’s os.Stat function is used to obtain metadata about files or directories. This metadata includes file name, size, permissions, and an indicator of whether the path represents a directory.
Using os.Stat is a quick way to verify file attributes before processing them in your application.
Copy
Ask AI
package mainimport ( "fmt" "os" "path/filepath")func main() { // Replace with your file path. fileInfo, err := os.Stat("/Users/priyanka/temp.txt") if err != nil { fmt.Println(err) return } fmt.Println("Name:", fileInfo.Name()) // e.g., temp.txt fmt.Println("Size:", fileInfo.Size()) // File size in bytes fmt.Println("Mode:", fileInfo.Mode()) // Permission bits fmt.Println("IsDir:", fileInfo.IsDir()) // false if it's a file}
Running the above code might produce an output similar to:
Golang provides convenient methods to read file contents. The os.ReadFile function reads the entire content of a file at once and returns a byte slice along with any error encountered.
Copy
Ask AI
package mainimport ( "fmt" "os")func main() { path := "/Users/priyanka/text.txt" data, err := os.ReadFile(path) if err != nil { fmt.Println(err) return } // Print raw byte slice output fmt.Println(data) // Convert to string for human-readable output fmt.Println(string(data))}
For a file containing “Hello World”, the output might look like:
package mainimport ( "fmt" "os")func main() { // Open file with append, create, and write-only flags, with 0644 permissions. file, err := os.OpenFile("/Users/priyanka/temp.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { fmt.Println(err) return } defer file.Close() // Append a string to the file. if _, err := file.WriteString("Hope you had a good day!"); err != nil { fmt.Println(err) }}
If the file does not exist, the os.O_CREATE flag ensures that it is created with the specified permissions. If the file exists, the string is appended to the current content.
In this article, we covered how to construct file paths, retrieve file metadata, read file contents (both entirely and in chunks), and write or append data to files using Golang. This foundational knowledge is essential for effectively managing files in your applications.