Introduction to File Handling
File handling refers to the process of creating, reading, writing, updating, and deleting files stored on a computer’s file system. In Go, file handling is part of standard input/output (I/O) operations and is handled mainly using the os, io, and bufio packages.
File handling allows programs to:
- Store data permanently
- Read configuration files
- Process logs
- Handle large datasets
- Exchange data between programs
Packages Used for File Handling in Go
Go provides powerful built-in packages for file I/O:
| Package | Purpose |
|---|---|
os | File creation, opening, deleting |
io | Low-level I/O primitives |
bufio | Buffered I/O (efficient reading/writing) |
fmt | Formatted input/output |
ioutil (deprecated) | Older file utilities (replaced by os & io) |
Creating a File in Go
Using os.Create()
os.Create() creates a new file.
If the file already exists, it truncates (clears) the file.
package main
import (
"os"
)
func main() {
file, err := os.Create("example.txt")
if err != nil {
panic(err)
}
defer file.Close()
}
Explanation
- Returns a file pointer
- Must always close the file
defer file.Close()ensures cleanup
Opening an Existing File
Using os.Open()
Used for read-only access.
file, err := os.Open("example.txt")
if err != nil {
panic(err)
}
defer file.Close()
Using os.OpenFile()
Allows full control over file access modes.
file, err := os.OpenFile(
"example.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0644,
)
File Flags
| Flag | Meaning |
|---|---|
os.O_RDONLY | Read only |
os.O_WRONLY | Write only |
os.O_RDWR | Read & write |
os.O_CREATE | Create if not exists |
os.O_APPEND | Append to file |
os.O_TRUNC | Truncate file |
Writing to a File
Writing Using WriteString()
file, _ := os.Create("data.txt")
defer file.Close()
file.WriteString("Hello, Go File Handling\n")
Writing Using fmt.Fprintln()
fmt.Fprintln(file, "This is a line written using fmt")
Writing Using bufio.Writer (Recommended)
Buffered writing is faster.
writer := bufio.NewWriter(file)
writer.WriteString("Buffered writing in Go\n")
writer.Flush()
Reading from a File
Reading Using os.ReadFile() (Simple)
data, err := os.ReadFile("example.txt")
if err != nil {
panic(err)
}
fmt.Println(string(data))
Best for small files.
Reading Using bufio.Scanner (Line by Line)
file, _ := os.Open("example.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
Used for:
- Log files
- Text processing
- Line-based input
Reading Using bufio.Reader
reader := bufio.NewReader(file)
line, _ := reader.ReadString('\n')
fmt.Println(line)
Appending to a File
Appending adds content without deleting existing data.
file, _ := os.OpenFile(
"example.txt",
os.O_APPEND|os.O_WRONLY,
0644,
)
defer file.Close()
file.WriteString("New appended line\n")
Deleting a File
Use os.Remove().
err := os.Remove("example.txt")
if err != nil {
panic(err)
}
Checking if a File Exists
if _, err := os.Stat("example.txt"); err == nil {
fmt.Println("File exists")
} else {
fmt.Println("File does not exist")
}
Getting File Information
Use os.Stat().
info, _ := os.Stat("example.txt")
fmt.Println("Name:", info.Name())
fmt.Println("Size:", info.Size())
fmt.Println("Permissions:", info.Mode())
fmt.Println("Modified:", info.ModTime())
File Permissions in Go
Permissions use Unix-style notation.
| Value | Meaning |
|---|---|
0644 | Owner read/write, others read |
0755 | Executable permissions |
0600 | Owner only |
Handling Errors in File I/O
Error handling is critical in Go.
file, err := os.Open("missing.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
Go forces explicit error checking, improving reliability.
Copying File Contents
source, _ := os.Open("a.txt")
defer source.Close()
destination, _ := os.Create("b.txt")
defer destination.Close()
io.Copy(destination, source)
Reading User Input and Writing to File
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
input, _ := reader.ReadString('\n')
file, _ := os.Create("user.txt")
defer file.Close()
file.WriteString(input)
File Handling Best Practices
- Always close files
- Use
defer - Prefer buffered I/O
- Handle errors properly
- Avoid reading large files fully into memory
Common Mistakes in Go File Handling
- Forgetting
file.Close() - Ignoring errors
- Using deprecated
ioutilpackage - Overwriting files unintentionally
- Not flushing buffered writers
Practical Example: Log File Writer
file, _ := os.OpenFile("log.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0644)
defer file.Close()
log := bufio.NewWriter(file)
log.WriteString("Application started\n")
log.Flush()
Summary
- Go provides robust file I/O using
os,io, andbufio - Supports file creation, reading, writing, appending, and deletion
- Explicit error handling ensures safety
- Buffered I/O improves performance
- Essential for backend systems, CLI tools, and system programs
Leave a Reply