✂️ Go – Truncate File with os.Truncate
: Syntax, Examples & Safety (2025 Guide)
🧲 Introduction – Why Truncate a File in Go?
In Go, you can truncate (cut down) a file using the built-in os.Truncate()
function. This is useful when you want to:
- Clear the contents of a log or temp file
- Limit file size for memory or disk usage
- Reset a file without deleting it
🎯 In this guide, you’ll learn:
- How to truncate a file in Go
- Set file size to 0 or custom length
- Handle permission and file-not-found errors
- Real-world use cases and safety tips
✅ Example – Truncate File to Zero Bytes
package main
import (
"fmt"
"os"
)
func main() {
err := os.Truncate("log.txt", 0)
if err != nil {
fmt.Println("Truncate failed:", err)
} else {
fmt.Println("File truncated successfully.")
}
}
📤 Output:
File truncated successfully.
✅ This clears all content in log.txt
by setting its size to 0
.
🧪 Truncate File to Custom Size
err := os.Truncate("data.txt", 10)
✅ Keeps the first 10 bytes of the file and discards the rest.
⚠️ If the file is smaller than 10 bytes, it will be padded with null bytes.
📂 Check If File Exists Before Truncating
if _, err := os.Stat("log.txt"); os.IsNotExist(err) {
fmt.Println("File does not exist")
} else {
os.Truncate("log.txt", 0)
}
✅ Prevents unnecessary os.Truncate
call on non-existent files.
🔒 Common Errors & Handling
Error Type | Cause |
---|---|
file not found | The file path doesn’t exist |
permission denied | No write access to the file |
invalid argument | Negative size provided |
✅ Always validate path and permissions before truncating.
🛠 Alternative – Truncate via File Object
file, err := os.OpenFile("temp.txt", os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
defer file.Close()
err = file.Truncate(0)
✅ Useful if you already have an os.File
object open.
🧠 Best Practices
Tip | Why It Helps |
---|---|
✅ Use os.Truncate() for quick resets | Efficient log cleanup without delete+recreate |
✅ Always check file access rights | Prevent runtime errors |
❌ Don’t truncate open shared files | May affect other processes |
✅ Log truncation actions | For audit and debugging |
📌 Summary – Recap & Next Steps
Go’s os.Truncate()
offers a clean and efficient way to shrink or clear files. It’s great for log rotation, resetting cache, or cleaning up large output files without deleting them.
🔍 Key Takeaways:
os.Truncate("file.txt", 0)
clears the file- You can keep the first N bytes with a custom size
- Handles padding or shrinking depending on target length
- Use error handling and file checks for safe operation
⚙️ Next: Explore Appending to Files, File Rotation, or Managing Temp Files in Go.
❓ FAQs – Go Truncate File
❓ What does os.Truncate()
do in Go?
✅ It sets the file’s size to the specified number of bytes, trimming or padding as needed.
❓ Will truncating a file delete it?
❌ No. It clears the content, but the file still exists.
❓ How can I reset a log file?
✅ Use os.Truncate("log.txt", 0)
to empty it.
❓ Can I truncate a file that is being read by another process?
⚠️ Yes, but be careful—other processes may crash or behave unpredictably.
❓ What happens if the file doesn’t exist?
✅ os.Truncate()
returns an error. Use os.Stat()
to check existence first.
Share Now :