Skip to content

Instantly share code, notes, and snippets.

@hidva
Created September 17, 2016 03:27
Show Gist options
  • Save hidva/dd82547d816c6211c1650333d45366df to your computer and use it in GitHub Desktop.
Save hidva/dd82547d816c6211c1650333d45366df to your computer and use it in GitHub Desktop.
Golang 将文件重命名为一个唯一的文件
import (
"os"
"github.com/satori/go.uuid"
"github.com/williamsandrew/go-xchg"
"golang.org/x/sys/unix"
)
func UniqueRename(oldpath, newpath_dir, newpath_prefix string) (newpath string, err error) {
newpath_prefix = newpath_dir + "/" + newpath_prefix
GetRandomString := func() string {
return uuid.NewV4().String()
}
// 测试需要.
// i := 1
// GetRandomString := func() string {
// i++
// return fmt.Sprintf("%d", i)
// }
for {
newpath = newpath_prefix + GetRandomString()
err = xchg.Renameat2(unix.AT_FDCWD, oldpath, unix.AT_FDCWD, newpath, xchg.NOREPLACE)
if os.IsExist(err) {
continue
}
break
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment