Created
September 17, 2016 01:43
-
-
Save hidva/ca5f6dc9695c60bd9a84d071acc57622 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" | |
) | |
func UniqueFile(dir, prefix string, flags int, perm os.FileMode) (f *os.File, err error) { | |
unique_file_prefix := dir + "/" + prefix | |
flags |= os.O_EXCL | os.O_CREATE | |
GetRandomString := func() string { | |
return uuid.NewV4().String() | |
} | |
for { | |
unique_file_path := unique_file_prefix + GetRandomString() | |
f, err = os.OpenFile(unique_file_path, flags, perm) | |
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