diff --git a/base/docs/helpdb.jl b/base/docs/helpdb.jl index e93a0095f2dd5..9bd5801833022 100644 --- a/base/docs/helpdb.jl +++ b/base/docs/helpdb.jl @@ -6114,9 +6114,9 @@ See also: :func:`extrema` that returns ``(minimum(x), maximum(x))`` minmax doc""" - mktemp([parent=tempdir()]) + mktemp([parent=tempdir()]; suffix="") -Returns `(path, io)`, where `path` is the path of a new temporary file in `parent` and `io` is an open file object for this path. +Returns `(path, io)`, where `path` is the path of a new temporary file in `parent` (with suffix `suffix`) and `io` is an open file object for this path. """ mktemp(?) diff --git a/base/file.jl b/base/file.jl index afd1ed3652c91..d650c59ee08bd 100644 --- a/base/file.jl +++ b/base/file.jl @@ -188,9 +188,9 @@ end tempdir() = dirname(tempname()) # Create and return the name of a temporary file along with an IOStream -function mktemp(parent=tempdir()) - b = joinpath(parent, "tmpXXXXXX") - p = ccall(:mkstemp, Int32, (Ptr{UInt8},), b) # modifies b +function mktemp(parent=tempdir(); suffix="") + b = joinpath(parent, "tmpXXXXXX$suffix") + p = ccall(:mkstemps, Int32, (Ptr{UInt8}, Cint), b, length(suffix)) systemerror(:mktemp, p == -1) return (b, fdio(p, true)) end @@ -225,8 +225,19 @@ function tempname(temppath::AbstractString,uunique::UInt32) resize!(tname,lentname+1) return utf8(UTF16String(tname)) end -function mktemp(parent=tempdir()) +function mktemp(parent=tempdir(); suffix="") filename = tempname(parent, UInt32(0)) + if length(suffix) > 0 + fnlen = length(filename) + if fnlen < 4 || lowercase(filename[fnlen-3:end]) != ".tmp" + error("mktemp failed: invalid result by GetTempFileName") + end + new_filename = filename[1:fnlen-4] * suffix + # NOTE: new_filename is not guaranteed to be nonexistent, + # but at least then mv will error out. + mv(filename, new_filename) + filename = new_filename + end return (filename, Base.open(filename, "r+")) end function mktempdir(parent=tempdir()) @@ -246,8 +257,8 @@ function mktempdir(parent=tempdir()) end end -function mktemp(fn::Function, parent=tempdir()) - (tmp_path, tmp_io) = mktemp(parent) +function mktemp(fn::Function, parent=tempdir(); suffix="") + (tmp_path, tmp_io) = mktemp(parent, suffix=suffix) try fn(tmp_path, tmp_io) finally diff --git a/test/file.jl b/test/file.jl index f8999120bcdf7..3a38d4695f9fe 100644 --- a/test/file.jl +++ b/test/file.jl @@ -219,6 +219,11 @@ close(f) @test readall(p) == "Here is some text" rm(p) +mktemp(suffix=".foo") do p, f + @test isfile(p) == true + @test endswith(p, ".foo") == true +end + let tmp_path = mktemp() do p, io @test isfile(p)