跳转至

os.Truncate

os.Truncate 截断文件到目标大小,如果文件的大小已经小于目标大小了,那么 os.Truncate 不会再截断。另一个比较特别的地方是 os.Truncate 不返回 *os.File ,而是就地操作的。

package main

import (
    "fmt"
    "log/slog"
    "os"
)

func main() {
    fileName := "/tmp/u.log"
    targetSize := int64(400)
    err := os.Truncate(fileName, targetSize)
    if err != nil {
        slog.Error(err.Error())
    } else {
        slog.Info(fmt.Sprintf("file '%s' truncated to %d byte(s) \n", fileName, targetSize))
    }
}