Golang 生成带扩展名的唯一文件名

标签 go temporary-files

我想在 Golang 中生成带有扩展名的唯一文件名。非常类似于 ioutil.TempFile,它只需要前缀。

这已在论坛中多次提出https://groups.google.com/forum/#!topic/golang-nuts/PHgye3Hm2_0 Go 似乎非常有意不将该功能添加到 TempFile。

那么建议的处理方法是什么?我应该只复制/粘贴 TempFile 代码并添加后缀参数吗?

最佳答案

更新(2020年:原答案是2015年的)

Laxanswer 所述,Go 1.11(2018 年 4 月)已将 TempFile 前缀更改为模式。

commit 191efbc之后从CL 105675issue 4896

Users of TempFile need to be able to supply the suffix, especially when using operating systems that give semantic meaning to the filename extension such as Windows.
Renaming the file to include an extension after the fact is insufficient as it could lead to race conditions.

If the string given to TempFile includes a "*", the random string replaces the "*".

For example "myname.*.bat" will result in a random filename such as "myname.123456.bat".

If no "*' is included the old behavior is retained, and the random digits are appended to the end.

If multiple "*" are included, the final one is replaced, thus permitting a pathological programmer to create filenames such as "foo*.123456.bat" but not "foo.123456.*.bat"


原始答案(2015 年)

Should I just copy/paste the TempFile code and add in a suffix parameter?

这是一种方式。
另一种方法是快速——粗略——实现,如在 this project 中:

// TempFileName generates a temporary filename for use in testing or whatever
func TempFileName(prefix, suffix string) string {
    randBytes := make([]byte, 16)
    rand.Read(randBytes)
    return filepath.Join(os.TempDir(), prefix+hex.EncodeToString(randBytes)+suffix)
}

正如下面的 James Henstridge comments,这是一个原始函数:

That function can return file names that already exist, for instance. Such an API should be creating the file by opening it with O_CREAT | O_EXCL to ensure that no one else creates the file between deciding on the name and creating the file.

上面那个粗略的函数仅说明了使用 rand.Read() 生成文件名。

但其他检查都在io/ioutil/tempfile.go中。
3of3 suggests 使用 math.rand 中的函数而不是复制 random number generator in io/ioutil/tempfile.go

关于Golang 生成带扩展名的唯一文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005865/

相关文章:

python - 如何使用 python 在 google app engine blobstore 上创建一个简单的虚拟文件系统?

mongodb - 使用 MongoDB 和 Golang 没有解码器错误

Go 中的 CSV 解析器因尾随空格而中断

eclipse - goclipse goarch 设置重要吗?

Python 临时文件 : broken or am I doing it wrong?

Python:tempfile.mkdtemp 和 tempfile.TemporaryDirectory 之间的区别

file - 为什么在Go中写入已删除的文件不会返回错误?

go 函数 - panic : runtime error: invalid memory address or nil pointer dereference

c++ - 在 C++ 中执行二进制 tmpfile

windows - 删除使用 TempFile 创建的锁定文件