Created
September 17, 2016 03:27
-
-
Save hidva/dd82547d816c6211c1650333d45366df to your computer and use it in GitHub Desktop.
Golang 将文件重命名为一个唯一的文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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