Go os.Stat and FileInfo.Size
Measure how many bytes a saved receipt occupies before attaching it to a message.
A simple example
os.Stat and FileInfo.Size
- Start with A regular file containing ASCII AB
- Do this Measure its length
- Result 2 bytes
Syntax
info.Size()
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goCheck a receipt attachment size
An office is preparing receipts for transfer and needs to budget storage. Identify which size the program measures, especially when a receipt is also stored inside a compressed archive.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
folder, err := os.MkdirTemp("", "receipts")
if err != nil { panic(err) }
defer os.RemoveAll(folder)
path := filepath.Join(folder, "today.txt")
if err := os.WriteFile(path, []byte("milk"), 0600); err != nil { panic(err) }
info, err := os.Stat(path)
if err != nil { panic(err) }
fmt.Println(info.Size())
}
4
The receipt contains the four ASCII bytes in milk. No newline is written.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
What to watch for
File sizes are measured in bytes. Text character counts can differ.