标签归档:清理文件

golang 删除七天前的文件

使用golang 清理备份文件。

package main

import (
	//"flag"
	"fmt"
	"os"
	"path/filepath"
	"time"
)

const (
	diff_time = 3600 * 24 * 7
)

func main() {
	//flag.Parse()
	//root := flag.Arg(0)
	root := "."
	getFilelist(root)
}

func getFilelist(path string) {
	now_time := time.Now().Unix() //当前时间,使用Unix时间戳
	err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		file_time := f.ModTime().Unix()
		/*
			fmt.Println(file_time)
			fmt.Println(now_time)
			fmt.Println("---", diff_time)
			fmt.Println(now_time - file_time)
		*/
		if (now_time - file_time) > diff_time { //判断文件是否超过7天
			fmt.Printf("Delete file %v !\r\n", path)
			os.RemoveAll(path)
		} //else {
		//println(path)
		//}
		return nil
	})
	if err != nil {
		fmt.Printf("filepath.Walk() returned %v\r\n", err)
	}
}

 

参考文档:
http://www.cnblogs.com/sevenyuan/archive/2013/02/28/2937275.html
https://github.com/jemygraw/GoStandardLibrary-Chinese/blob/master/os/os.md