Secure temporary file: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(Replaced posix function by function "createTempFile" from new module "tempfiles" provided by version 1.6.0.) |
m (→{{header|Wren}}: Minor tidy) |
||
(14 intermediate revisions by 10 users not shown) | |||
Line 14:
This example creates a temporary file, writes to the file, then reads from the file.
<
procedure Temp_File is
Line 27:
Get_Line(File => Temp, Item => Contents, Last => Length);
Put_Line(Contents(1..Length));
end Temp_File;</
=={{header|
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
The file is automatically deleted when closed.
<
IF file% = 0 ERROR 100, "Failed to open temp file"
PRINT #file%, "Hello world!"
Line 58 ⟶ 59:
IF hfile% = INVALID_HANDLE_VALUE THEN = 0
@hfile%(chan%) = hfile%
= chan%</
'''Output:'''
<pre>
Hello world!
</pre>
==={{header|FreeBASIC}}===
{{trans|BBC BASIC}}
The file is deleted when closed.
<syntaxhighlight lang="vb">Dim As Long f
Dim As String message
f = Freefile
Open "temp.txt" For Output As #f
If Err > 0 Then Print "Failed to open temp"; f : End
Print #f, "Hello world!"
Close #f
Open "temp.txt" For Input As #f
Line Input #f, message
Close #f
Print message
Shell "del temp.txt"
Sleep</syntaxhighlight>
=={{header|C}}==
<
#include <stdio.h>
Line 78 ⟶ 100:
time you open it. */
return 0;
}</
The following {{works with|POSIX}}
<
#include <stdio.h>
Line 92 ⟶ 114:
close(fd);
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.IO;
Console.WriteLine(Path.GetTempFileName());</
=={{header|C++}}==
<syntaxhighlight lang="c++">
#include <cstdio>
int main() {
// Creates and opens a temporary file with a unique auto-generated filename.
// If the program closes the file, the file is automatically deleted.
// The file is also automatically deleted if the program exits normally.
std::FILE* temp_file_pointer = std::tmpfile();
// Using functions which take a file pointer as an argument
std::fputs("Hello world", temp_file_pointer);
std::rewind(temp_file_pointer);
char buffer[12];
std::fgets(buffer, sizeof buffer, temp_file_pointer);
printf(buffer);
}
</syntaxhighlight>
{{ out }}
<pre>
Hello world
</pre>
=={{header|Clojure}}==
It is good practice to explicitly delete temp files immediately once they've been used.
<
; insert logic here that would use temp-file
(.delete temp-file))</
=={{header|D}}==
{{works with|Tango}}
<
import tango.io.TempFile, tango.io.Stdout ;
Line 123 ⟶ 168:
// both can only be accessed by the current user (the program?).
}</
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.IOUtils}}
<syntaxhighlight lang="delphi">
program Secure_temporary_file;
Line 151 ⟶ 196:
writeln(FileName);
Readln;
end.</
=={{header|Emacs Lisp}}==
<code>make-temp-file</code> creates a new empty temporary file, with perms "0700" so read-write to the current user only.
<
;; => "/tmp/prefix25452LPe"</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
printfn $"%s{System.IO.Path.GetTempFileName()}"
</syntaxhighlight>
{{out}}
<pre>
/tmp/tmpEuSgiY.tmp
</pre>
For the cynical who may not believe the file has been created
</pre>
nigel@nigel:/tmp$ ls *.tmp
tmpEuSgiY.tmp
</pre>
=={{header|Fortran}}==
Supposing F is an integer variable, whose value might be 10. This is the I/O unit number, and would be used in READ(F,''etc.'' and WRITE(F,''etc.'' statements. <
Other attributes might be specified depending on the intended usage, but note that no file name is given. When the file is closed, its storage vanishes back to the file system.
Line 170 ⟶ 227:
=={{header|Go}}==
Use <code>[https://golang.org/pkg/io/ioutil/#TempFile ioutil.TempFile]</code>
<
import (
Line 201 ⟶ 258:
// The defer statements above will close and remove the
// temporary file here (or on any return of this function).
}</
{{out}}
<pre>
Line 208 ⟶ 265:
=={{header|Groovy}}==
<
// There is no requirement in the instructions to delete the file.
//file.deleteOnExit()
println file</
Output:
Line 219 ⟶ 276:
=={{header|Haskell}}==
<
main = do (pathOfTempFile, h) <- openTempFile "." "prefix.suffix" -- first argument is path to directory where you want to put it
-- do stuff with it here; "h" is the Handle to the opened file
return ()</
=={{header|HicEst}}==
<
! A scratch file is automatically deleted upon process termination.
Line 237 ⟶ 294:
OPEN( FIle='DenyForOthers', DenyREAdWRIte, IOStat=ErrNr)
WRITE(FIle='DenyForOthers') "something"
WRITE(FIle='DenyForOthers', DELETE=1)</
=={{header|Icon}} and {{header|Unicon}}==
Line 243 ⟶ 300:
A posix-based solution that works in both languages:
<
write("Creating: ",fName := !open("mktemp","rp"))
write(f := open(fName,"w"),"Hello, world")
close(f)
end</
=={{header|Java}}==
<
import java.io.IOException;
Line 265 ⟶ 322:
}
}
}</
Alternative example
<syntaxhighlight lang="java">
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public final class SecureTemporaryFile {
public static void main(String[] args) throws IOException {
// Create a temporary file in the directory D:\.
// We should use java.nio.file.Files instead of the old java.io.File, as it is more secure.
// If the file cannot be created, it will throw an exception.
Path temporaryFilePath = Files.createTempFile(Path.of("D:/"), "example", ".tmp");
// For uniqueness, the Java API will insert a random number between the given prefix
// and the file extension.
System.out.println("Temporary file created: " + temporaryFilePath);
// Opening it with the following option will cause the file to be deleted when it is closed.
BufferedWriter tempFileWriter = Files.newBufferedWriter(
temporaryFilePath, StandardOpenOption.DELETE_ON_CLOSE);
// ... write to file, read it back in, close it...
}
}
</syntaxhighlight>
{{ out }}
<pre>
Temporary file created: D:\example12312088502442779987.tmp
</pre>
=={{header|Julia}}==
{{works with|Linux}} On Unix systems, Julia calls <code>mkstemp</code> to securely open a temporary file. This is likely multi-thread safe, check your system documentation for verification. This code should also work on Windows, but I've not verified that.
<syntaxhighlight lang="julia">
msg = "Rosetta Code, Secure temporary file, implemented with Julia."
Line 277 ⟶ 367:
close(tio)
println("\"", msg, "\" written to ", fname)
</syntaxhighlight>
Files written to <code>\tmp</code> persist for the login session, and are thus truly temporary. If the environment variable <code>TMPDIR</code> is set, the temporary file is created in this directory. In this case, the file may not be properly temporary.
<syntaxhighlight lang="julia">
ENV["TMPDIR"] = pwd()
(fname, tio) = mktemp()
Line 286 ⟶ 376:
close(tio)
println("\"", msg, "\" written to ", fname)
</syntaxhighlight>
{{out}}
Line 305 ⟶ 395:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.io.path.createTempFile
import kotlin.io.path.deleteExisting
fun main() {
val tempFilePath = createTempFile("example", ".tmp")
println("Temporary file created: $tempFilePath")
tempFilePath.deleteExisting()
}</syntaxhighlight>
Sample output:
{{out}}
<pre>
Temporary file created: /tmp/example14437465325231438926.tmp
</pre>
=={{header|Lua}}==
<
-- do some file operations
fp:close()</
=={{header|M2000 Interpreter}}==
tmp files automatic deleted when Environment end (per running environment)
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
\\ we get a tempname$ choosed from Windows
Line 356 ⟶ 440:
Checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Close[tmp]</
=={{header|Nanoquery}}==
<
def guaranteedTempFile()
Line 387 ⟶ 471:
// return the file reference
return $tempfile
end</
=={{header|NetRexx}}==
{{incomplete|NetRexx|JVM Windows related bug workaround JDK-4715154}}<
options replace format comments java crossref symbols binary
Line 421 ⟶ 505:
end
return
</syntaxhighlight>
=={{header|Nim}}==
{{Works with|Nim|1.6.0}}
<
let (file, path) = createTempFile(prefix = "", suffix = "")
Line 433 ⟶ 517:
for line in path.lines:
echo line
removeFile(path)</
{{out}}
<pre>/tmp/th7lDdkH created.
Line 439 ⟶ 523:
=={{header|OCaml}}==
From the module Filename, one can use the functions [
<
- : string = "/home/blue_prawn/tmp/prefix.301f82.suffix"</
=={{header|Octave}}==
Octave has several related functions
<
filename = tmpnam (...); % generates temporary file name, but does not open file
[FID, NAME, MSG] = mkstemp (TEMPLATE, DELETE); % Return the file ID corresponding to a new temporary file with a unique name created from TEMPLATE.</
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{libheader|SysUtils}}
<
uses
Line 466 ⟶ 550:
writeln (tempFile, 5);
close (tempFile);
end.</
=={{header|Perl}}==
function interface:
<
$fh = tempfile();
($fh2, $filename) = tempfile(); # this file stays around by default
print "$filename\n";
close $fh;
close $fh2;</
object-oriented interface:
<
$fh = new File::Temp;
print $fh->filename, "\n";
close $fh;</
=={{header|Phix}}==
The temp_file() function (see builtins/pfile.e) can be used for this:
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (file i/o)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">temp_file</span><span style="color: #0000FF;">())</span>
<span style="color: #0000FF;">{</span><span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">name</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">temp_file</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"myapp/tmp"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"data"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"log"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"wb"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">({</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #000000;">name</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">delete_file</span><span style="color: #0000FF;">(</span><span style="color: #000000;">name</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 499 ⟶ 586:
=={{header|PHP}}==
<
// do stuff with $fh
fclose($fh);
Line 507 ⟶ 594:
$filename = tempnam('/tmp', 'prefix');
echo "$filename\n";
// open $filename and do stuff with it</
=={{header|PicoLisp}}==
Line 516 ⟶ 603:
they are (e.g. because such a file name is passed to a child process), explicit
locks with the 'ctl' functions are possible.
<
-> 123
Line 527 ⟶ 614:
(let N (read) # Atomic increment
(out F (println (inc N))) ) ) ) )
-> 124</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$tempFile = [System.IO.Path]::GetTempFileName()
Set-Content -Path $tempFile -Value "FileName = $tempFile"
Get-Content -Path $tempFile
Remove-Item -Path $tempFile
</syntaxhighlight>
{{Out}}
<pre>
Line 542 ⟶ 629:
=={{header|PureBasic}}==
<
Protected a, Result$
Line 566 ⟶ 653:
CloseFile(File)
EndIf
EndIf</
=={{header|Python}}==
Line 573 ⟶ 660:
<
>>> invisible = tempfile.TemporaryFile()
>>> invisible.name
Line 581 ⟶ 668:
'/tmp/tmpZNfc_s'
>>> visible.close()
>>> invisible.close()</
Line 587 ⟶ 674:
<
try:
# use the path or the file descriptor
finally:
os.close(fd)</
=={{header|Racket}}==
<
#lang racket
(make-temporary-file)
</syntaxhighlight>
=={{header|Raku}}==
Line 606 ⟶ 693:
Almost verbatim from the synopsis:
<syntaxhighlight lang="raku"
# Generate a temp file in a temp dir
Line 625 ⟶ 712:
# specify a prefix, a suffix, or both for the filename
my ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt"));</
=={{header|REXX}}==
REXX uses the underlying OS to create and delete the file.
<
parse arg tFID # . /*obtain optional argument from the CL.*/
if tFID=='' | tFID=="," then tFID= 'TEMP.FILE' /*Not specified? Then use the default.*/
Line 659 ⟶ 746:
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error***' arg(1); say; exit 13 /*issue an error message to the term. */</
{{out|output|text= when using the default input:}}
<pre>
Line 675 ⟶ 762:
=={{header|Ruby}}==
<syntaxhighlight lang
f.path # =>
f.close
f.unlink # => #<Tempfile: (closed)></syntaxhighlight>
=={{header|Rust}}==
<
use tempfile::tempfile;
Line 696 ⟶ 779:
println!("{:?}", fh);
}</
{{out}}
<pre>
Line 703 ⟶ 786:
=={{header|Scala}}==
<
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
Line 720 ⟶ 803:
} catch {
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}</
=={{header|Sidef}}==
<
var fh = tmpfile.new(UNLINK => 0);
say fh.filename;
fh.print("Hello, World!\n");
fh.close;</
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "tmpfile" );
pragma annotate( description, "Create a temporary file, securely and exclusively" );
pragma annotate( description, "(opening it such that there are no possible race" );
pragma annotate( description, "conditions). It's fine assuming local filesystem" );
pragma annotate( description, "semantics (NFS or other networking filesystems can" );
pragma annotate( description, "have signficantly more complicated semantics for" );
pragma annotate( description, "satisfying the 'no race conditions' criteria). The" );
pragma annotate( description, "function should automatically resolve name collisions" );
pragma annotate( description, "and should only fail in cases where permission is" );
pragma annotate( description, "denied, the filesystem is read-only or full, or similar" );
pragma annotate( description, "conditions exist (returning an error or raising an" );
pragma annotate( description, "exception as appropriate to the language/environment)." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Secure_temporary_file" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure tmpfile is
temp : file_type;
contents : string;
begin
? "Creating a temporary file";
create( temp );
put_line( temp, "Hello World");
? "Reading a temporary file";
reset( temp, in_file);
contents := get_line( temp );
put_line( "File contains: " & contents );
? "Discarding a temporary file";
close( temp );
end tmpfile;</syntaxhighlight>
=={{header|Standard ML}}==
<
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
Will store the name of the file in the variable <code>filenameVar</code> and an open read-write channel on the file in the variable <code>chan</code>.
<syntaxhighlight lang
Note that because we're asking for the filename in the script, Tcl does not automatically clean the file. (There are cases where auto-cleaning would be really unwanted.) If we hadn't asked for it, the file would be automatically deleted (at a time that depends on platform constraints).
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
tmpfile="test.txt"
Line 746 ⟶ 867:
FILE $tmpfile = text
- tmpfile "test.txt" can only be accessed by one user an will be deleted upon programm termination
</syntaxhighlight>
=={{header|UNIX Shell}}==
Line 755 ⟶ 876:
thereunder.
<
TRY=0
while :; do
Line 767 ⟶ 888:
cd "$MYTMP" || {
echo "Temporary directory failure on $MYTMP" >&2
exit 1; }</
Note that the shell special variable $$ (the PID of the currently ''exec()''-ed shell) is unique at any given
Line 778 ⟶ 899:
{{libheader|Wren-ioutil}}
{{libheader|Wren-fmt}}
<
import "./ioutil" for File, FileUtil
import "./fmt" for Fmt
var rand = Random.new()
Line 807 ⟶ 928:
System.print(File.read(tmp))
File.delete(tmp)
System.print("Temporary file deleted.")</
{{out}}
|