Golang os.Truncate(), os.File.Sync() and os.File.Stat() functions example
package os
Golang os.Truncate(), os.File.Sync() and os.File.Stat() functions usage example
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
panic(err)
}
defer file.Close()
fileInfo, err := file.Stat() // use Stat() to get file size
if err != nil {
panic(err)
}
fmt.Printf("File size before truncate %d \n", fileInfo.Size())
os.Truncate(file.Name(), 1024)
file.Sync() // optional - incase the file size is super big or power failure
newFileInfo, err := file.Stat()
if err != nil {
panic(err)
}
fmt.Printf("File size after truncate %d \n", newFileInfo.Size())
}
Sample output :
File size before truncate 242731
File size after truncate 1024
References :
http://golang.org/pkg/os/#File.Stat
Advertisement
Something interesting
Tutorials
+13k Golang : Calculate elapsed years or months since a date
+8.6k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+21.2k Golang : Clean up null characters from input data
+23.9k Golang : Fix type interface{} has no field or no methods and type assertions example
+14.3k Golang : How to shuffle elements in array or slice?
+15.4k Golang : Find location by IP address and display with Google Map
+10.5k Golang : Create matrix with Gonum Matrix package example
+13.2k Golang : Convert(cast) int to int64
+6.3k Golang : Detect face in uploaded photo like GPlus
+10.1k Golang : Identifying Golang HTTP client request
+6.6k Golang : Totalize or add-up an array or slice example
+4.7k Adding Skype actions such as call and chat into web page examples