📂 Go – Read/Write File Without Truncation (os.OpenFile
Usage Guide)
🧲 Introduction – Why Read/Write Without Truncating?
By default, opening a file in write mode may truncate (clear) it. To preserve existing content while allowing read/write access, you need to explicitly configure file access using os.OpenFile
with the correct flags.
🎯 In this guide, you’ll learn:
- How to open a file for reading and writing without truncation
- Use
os.OpenFile
with proper mode and flags - Append vs overwrite vs preserve contents
- Best practices for safe read/write operations
✅ Example – Read and Write Without Truncating
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.OpenFile("example.txt", os.O_RDWR, 0644)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Read from file
buf := make([]byte, 100)
n, _ := file.Read(buf)
fmt.Println("Original content:")
fmt.Println(string(buf[:n]))
// Move cursor to end of file and write
file.WriteString("\nAppended line without truncating.")
}
✅ This opens example.txt
for both reading and writing while preserving its content.
🔑 os.OpenFile Flags Breakdown
Flag | Description |
---|---|
os.O_RDONLY | Open for read-only |
os.O_WRONLY | Open for write-only |
os.O_RDWR | Open for read & write |
os.O_APPEND | Always write to the end (append mode) |
os.O_CREATE | Create the file if it doesn’t exist |
os.O_TRUNC | Truncate file when opening (⚠️ avoid) |
✅ To preserve contents, do not use os.O_TRUNC
.
🔁 Append Without Overwriting
file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
file.WriteString("Appended content\n")
✅ os.O_APPEND
ensures data is added at the end, preserving all existing content.
⚙️ Read, Write & Create If Not Exists (Safe Mode)
file, err := os.OpenFile("data.txt", os.O_RDWR|os.O_CREATE, 0644)
✅ This:
- Reads and writes
- Creates the file if it doesn’t exist
- Does not truncate the file
🧠 Best Practices
Tip | Why It Helps |
---|---|
✅ Use `os.O_RDWR | os.O_CREATE` |
❌ Avoid os.O_TRUNC if preserving | Prevents accidental data loss |
✅ Always defer file.Close() | Ensures file is properly closed |
✅ Check cursor with Seek() | To control where writing happens |
📌 Summary – Recap & Next Steps
Go allows you to safely read and write files without losing data—simply configure the right OpenFile
flags. This is crucial for logs, caches, and state files where content must persist between operations.
🔍 Key Takeaways:
- Use
os.O_RDWR
oros.O_APPEND
for writing without truncating - Avoid
os.O_TRUNC
unless you intend to clear the file - Combine
os.O_CREATE
to create the file if missing - Use
Seek()
to manage write position when needed
⚙️ Next: Explore Go File Copying, Truncation Safety, or Buffered Writing with bufio.
❓ FAQs – Go Read/Write Without Truncating
❓ How do I prevent Go from truncating my file?
✅ Avoid using the os.O_TRUNC
flag with os.OpenFile
.
❓ Can I read and write to the same file?
✅ Yes, use os.O_RDWR
when opening the file.
❓ How do I append data instead of overwriting?
✅ Use os.O_APPEND
when opening the file.
❓ What if the file doesn’t exist?
✅ Add os.O_CREATE
to your flag set to create it if missing.
❓ How can I overwrite part of a file without truncating it all?
✅ Use file.Seek(offset, whence)
to reposition the write cursor manually.
Share Now :