Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Secure_temporary_file
note: Programming environment operations

View file

@ -0,0 +1,8 @@
;Task:
Create a temporary file, '''securely and exclusively''' (opening it such that there are no possible [[race condition|race conditions]]).
It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria).
The function should automatically resolve name collisions and should only fail in cases where permission is denied, the filesystem is read-only or full, or similar conditions exist (returning an error or raising an exception as appropriate to the language/environment).
<br><br>

View file

@ -0,0 +1,14 @@
with Ada.Text_Io; use Ada.Text_Io;
procedure Temp_File is
Temp : File_Type;
Contents : String(1..80);
Length : Natural;
begin
-- Create a temporary file
Create(File => Temp);
Put_Line(File => Temp, Item => "Hello World");
Reset(File => Temp, Mode => In_File);
Get_Line(File => Temp, Item => Contents, Last => Length);
Put_Line(Contents(1..Length));
end Temp_File;

View file

@ -0,0 +1,27 @@
file% = FNopentempfile
IF file% = 0 ERROR 100, "Failed to open temp file"
PRINT #file%, "Hello world!"
PTR#file% = 0
INPUT #file%, message$
CLOSE #file%
PRINT message$
END
DEF FNopentempfile
LOCAL pname%, hfile%, chan%
OPEN_EXISTING = 3
FILE_FLAG_DELETE_ON_CLOSE = &4000000
GENERIC_READ = &80000000
GENERIC_WRITE = &40000000
INVALID_HANDLE_VALUE = -1
DIM pname% LOCAL 260
FOR chan% = 5 TO 12
IF @hfile%(chan%) = 0 EXIT FOR
NEXT
IF chan% > 12 THEN = 0
SYS "GetTempFileName", @tmp$, "BBC", 0, pname%
SYS "CreateFile", $$pname%, GENERIC_READ OR GENERIC_WRITE, 0, 0, \
\ OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, 0 TO hfile%
IF hfile% = INVALID_HANDLE_VALUE THEN = 0
@hfile%(chan%) = hfile%
= chan%

View file

@ -0,0 +1,4 @@
using System;
using System.IO;
Console.WriteLine(Path.GetTempFileName());

View file

@ -0,0 +1,14 @@
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
FILE *fh = tmpfile(); /* file is automatically deleted when program exits */
/* do stuff with stream "fh" */
fclose(fh);
/* The C standard library also has a tmpnam() function to create a file
for you to open later. But you should not use it because someone else might
be able to open the file from the time it is created by this function to the
time you open it. */
return 0;
}

View file

@ -0,0 +1,12 @@
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char filename[] = "/tmp/prefixXXXXXX";
int fd = mkstemp(filename);
puts(filename);
/* do stuff with file descriptor "fd" */
close(fd);
return 0;
}

View file

@ -0,0 +1,3 @@
(let [temp-file (java.io.File/createTempFile "pre" ".suff")]
; insert logic here that would use temp-file
(.delete temp-file))

View file

@ -0,0 +1,15 @@
module tempfile ;
import tango.io.TempFile, tango.io.Stdout ;
void main(char[][] args) {
// create a temporary file that will be deleted automatically when out of scope
auto tempTransient = new TempFile(TempFile.Transient) ;
Stdout(tempTransient.path()).newline ;
// create a temporary file, still persist after the TempFile object has been destroyed
auto tempPermanent = new TempFile(TempFile.Permanent) ;
Stdout(tempPermanent.path()).newline ;
// both can only be accessed by the current user (the program?).
}

View file

@ -0,0 +1,24 @@
program Secure_temporary_file;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IOUtils;
var
FileName, buf: string;
begin
FileName := TPath.GetTempFileName;
with TFile.Open(FileName, TFileMode.fmCreate, TFileAccess.faReadWrite,
Tfileshare.fsNone) do
begin
buf := 'This is a exclusive temp file';
Write(buf[1], buf.Length * sizeof(char));
Free;
end;
writeln(FileName);
Readln;
end.

View file

@ -0,0 +1,2 @@
(make-temp-file "prefix")
;; => "/tmp/prefix25452LPe"

View file

@ -0,0 +1 @@
OPEN (F,STATUS = 'SCRATCH') !Temporary disc storage.

View file

@ -0,0 +1,17 @@
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

View file

@ -0,0 +1,32 @@
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
f, err := ioutil.TempFile("", "foo")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// We need to make sure we remove the file
// once it is no longer needed.
defer os.Remove(f.Name())
// … use the file via 'f' …
fmt.Fprintln(f, "Using temporary file:", f.Name())
f.Seek(0, 0)
d, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Wrote and read: %s\n", d)
// The defer statements above will close and remove the
// temporary file here (or on any return of this function).
}

View file

@ -0,0 +1,6 @@
def file = File.createTempFile( "xxx", ".txt" )
// There is no requirement in the instructions to delete the file.
//file.deleteOnExit()
println file

View file

@ -0,0 +1,5 @@
import System.IO
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 ()

View file

@ -0,0 +1,12 @@
! The "scratch" option opens a file exclusively for the current process.
! A scratch file is automatically deleted upon process termination.
OPEN( FIle='TemporaryAndExclusive', SCRatch, IOStat=ErrNr)
WRITE(FIle='TemporaryAndExclusive') "something"
WRITE(FIle='TemporaryAndExclusive', CLoSe=1) ! explicit "close" deletes file
! Without "scratch" access can be controlled by "denyread", "denywrite", "denyreadwrite" options.
OPEN( FIle='DenyForOthers', DenyREAdWRIte, IOStat=ErrNr)
WRITE(FIle='DenyForOthers') "something"
WRITE(FIle='DenyForOthers', DELETE=1)

View file

@ -0,0 +1,5 @@
procedure main()
write("Creating: ",fName := !open("mktemp","rp"))
write(f := open(fName,"w"),"Hello, world")
close(f)
end

View file

@ -0,0 +1,15 @@
import java.io.File;
import java.io.IOException;
public class CreateTempFile {
public static void main(String[] args) {
try {
//create a temp file
File temp = File.createTempFile("temp-file-name", ".tmp");
System.out.println("Temp file : " + temp.getAbsolutePath());
}
catch(IOException e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,7 @@
msg = "Rosetta Code, Secure temporary file, implemented with Julia."
(fname, tio) = mktemp()
println(fname, " created as a temporary file.")
println(tio, msg)
close(tio)
println("\"", msg, "\" written to ", fname)

View file

@ -0,0 +1,6 @@
ENV["TMPDIR"] = pwd()
(fname, tio) = mktemp()
println(fname, " created as a \"temporary\" file.")
println(tio, msg)
close(tio)
println("\"", msg, "\" written to ", fname)

View file

@ -0,0 +1,14 @@
// version 1.1.2
import java.io.File
fun main(args: Array<String>) {
try {
val tf = File.createTempFile("temp", ".tmp")
println(tf.absolutePath)
tf.delete()
}
catch (ex: Exception) {
println(ex.message)
}
}

View file

@ -0,0 +1,5 @@
fp = io.tmpfile()
-- do some file operations
fp:close()

View file

@ -0,0 +1,19 @@
Module Checkit {
\\ we get a tempname$ choosed from Windows
a$=tempname$
Try ok {
\\ we can use wide to export in utf-16le
\\ without wide we export as Ansi (set Local to desired language)
Rem Locale 1033 ' when no use of wide
Open a$ for wide output exclusive as #f
wait 10
\\ Notepad can't open, because we open it for exclusive use
Win "Notepad", a$
Print #f, "something"
Print "Press a key";Key$
Close #f
}
If error or not ok then Print Error$
Win "Notepad", a$
}
Checkit

View file

@ -0,0 +1,2 @@
tmp = OpenWrite[]
Close[tmp]

View file

@ -0,0 +1,25 @@
import Nanoquery.IO
def guaranteedTempFile()
// create a file object to generate temp file names
$namegen = new(File)
// generate a temp filename
$tempname = $namegen.tempFileName()
// file names are generated with uuids so they shouldn't repeat
// in the case that they do, generate new ones until the generated
// filename is unique
$tempfile = new(File, $tempname)
while ($tempfile.exists())
$tempname = $namegen.tempFileName()
$tempfile = new(File, $tempname)
end
// create the file and lock it from writing
$tempfile.create()
lock $tempfile.fullPath()
// return the file reference
return $tempfile
end

View file

@ -0,0 +1,31 @@
/* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method makeTempFile(prefix = String, suffix = String null, startDir = String null) -
public static signals IOException returns File
if startDir \= null then fStartDir = File(startDir)
else fStartDir = null
ff = File.createTempFile(prefix, suffix, fStartDir)
ff.deleteOnExit() -- make sure the file is deleted at termination
return ff
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
do
tempFiles = [ -
makeTempFile('rexx'), -
makeTempFile('rexx', '.rex'), -
makeTempFile('rexx', null, './tmp') -
]
loop fFile over tempFiles
fName = fFile.getCanonicalPath()
say 'Temporary file:' fName
end fFile
catch ex = IOException
ex.printStackTrace()
end
return

View file

@ -0,0 +1,9 @@
import std/[os, tempfiles]
let (file, path) = createTempFile(prefix = "", suffix = "")
echo path, " created."
file.writeLine("This is a secure temporary file.")
file.close()
for line in path.lines:
echo line
removeFile(path)

View file

@ -0,0 +1,2 @@
# Filename.temp_file "prefix." ".suffix" ;;
- : string = "/home/blue_prawn/tmp/prefix.301f82.suffix"

View file

@ -0,0 +1,3 @@
[FID, MSG] = tmpfile(); % Return the file ID corresponding to a new temporary
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.

View file

@ -0,0 +1,9 @@
$fh = tmpfile();
// do stuff with $fh
fclose($fh);
// file removed when closed
// or:
$filename = tempnam('/tmp', 'prefix');
echo "$filename\n";
// open $filename and do stuff with it

View file

@ -0,0 +1,14 @@
Program TempFileDemo;
uses
SysUtils;
var
tempFile: text;
begin
assign (Tempfile, GetTempFileName);
rewrite (tempFile);
writeln (tempFile, 5);
close (tempFile);
end.

View file

@ -0,0 +1,6 @@
use File::Temp qw(tempfile);
$fh = tempfile();
($fh2, $filename) = tempfile(); # this file stays around by default
print "$filename\n";
close $fh;
close $fh2;

View file

@ -0,0 +1,4 @@
use File::Temp;
$fh = new File::Temp;
print $fh->filename, "\n";
close $fh;

View file

@ -0,0 +1,8 @@
(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>
<!--

View file

@ -0,0 +1,12 @@
: (out (tmp "foo") (println 123)) # Write tempfile
-> 123
: (in (tmp "foo") (read)) # Read tempfile
-> 123
: (let F (tmp "foo")
(ctl F # Get exclusive lock
(in F
(let N (read) # Atomic increment
(out F (println (inc N))) ) ) ) )
-> 124

View file

@ -0,0 +1,4 @@
$tempFile = [System.IO.Path]::GetTempFileName()
Set-Content -Path $tempFile -Value "FileName = $tempFile"
Get-Content -Path $tempFile
Remove-Item -Path $tempFile

View file

@ -0,0 +1,25 @@
Procedure.s TempFile()
Protected a, Result$
For a = 0 To 9999
Result$ = GetTemporaryDirectory() + StringField(GetFilePart(ProgramFilename()),1,".")
Result$ + "_" + Str(ElapsedMilliseconds()) + "_(" + RSet(Str(a),4,"0") + ").tmp"
If FileSize(Result$) = -1 ; -1 = File not found
ProcedureReturn Result$
EndIf
Next
ProcedureReturn ""
EndProcedure
Define File, File$
File$ = TempFile()
If File$ <> ""
File = CreateFile(#PB_Any, File$)
If File <> 0
WriteString(File, "Some temporary data here...")
CloseFile(File)
EndIf
EndIf

View file

@ -0,0 +1,9 @@
>>> import tempfile
>>> invisible = tempfile.TemporaryFile()
>>> invisible.name
'<fdopen>'
>>> visible = tempfile.NamedTemporaryFile()
>>> visible.name
'/tmp/tmpZNfc_s'
>>> visible.close()
>>> invisible.close()

View file

@ -0,0 +1,5 @@
fd, path = tempfile.mkstemp()
try:
# use the path or the file descriptor
finally:
os.close(fd)

View file

@ -0,0 +1,31 @@
/*REXX pgm secures (a temporary file), writes to it, displays the file, then deletes it.*/
parse arg tFID # . /*obtain optional argument from the CL.*/
if tFID=='' | tFID=="," then tFID= 'TEMP.FILE' /*Not specified? Then use the default.*/
if #=='' | #=="," then #= 6 /* " " " " " " */
call lineout tFID /*insure file is closed. */
rc= 0
say '··· creating file: ' tFID
call lineout tFID,,1 /*insure file is open and at record 1. */
if rc\==0 then call ser rc 'creating file' tFID /*issue error if can't open the file. */
say '··· writing file: ' tFID
do j=1 for # /*write a half-dozen records to file. */
call lineout tFID, 'line' j /*write a record to the file. */
if rc\==0 then call ser rc 'writing file' tFID /*Have an error? Issue err msg.*/
end /*j*/
call lineout tFID /*close the file. */
say '··· reading/display file: ' tFID
do j=1 while lines(tFID)>0 /*read the entire file and display it. */
x= linein(tFID) /*read a record from the file. */
if rc\==0 then call ser rc 'reading file' tFID /*Have an error? Issue err msg.*/
say 'line ' j " of file" tFID":" x /*display a record to the term. */
end /*j*/
call lineout tFID /*close the file. */
say '··· erasing file: ' tFID
'ERASE' tFID /*erase the file. */
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. */

View file

@ -0,0 +1,2 @@
#lang racket
(make-temporary-file)

View file

@ -0,0 +1,20 @@
use File::Temp;
# Generate a temp file in a temp dir
my ($filename0,$filehandle0) = tempfile;
# specify a template for the filename
# * are replaced with random characters
my ($filename1,$filehandle1) = tempfile("******");
# Automatically unlink files at DESTROY (this is the default)
my ($filename2,$filehandle2) = tempfile("******", :unlink);
# Specify the directory where the tempfile will be created
my ($filename3,$filehandle3) = tempfile(:tempdir("/path/to/my/dir"));
# don't unlink this one
my ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink);
# specify a prefix, a suffix, or both for the filename
my ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt"));

View file

@ -0,0 +1,6 @@
require 'tempfile'
f = Tempfile.new('foo')
f.path # => "/tmp/foo20081226-307-10p746n-0"
f.close
f.unlink # => #<Tempfile: (closed)>

View file

@ -0,0 +1,10 @@
// 202100322 Rust programming solution
use tempfile::tempfile;
fn main() {
let fh = tempfile();
println!("{:?}", fh);
}

View file

@ -0,0 +1,18 @@
import java.io.{File, FileWriter, IOException}
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
try {
val file = File.createTempFile("_rosetta", ".passwd")
// Just an example how you can fill a file
using(new FileWriter(file))(writer => rawDataIter.foreach(line => writer.write(line)))
scala.compat.Platform.collectGarbage() // JVM Windows related bug workaround JDK-4715154
file.deleteOnExit()
println(file)
} catch {
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}

View file

@ -0,0 +1,5 @@
var tmpfile = require('File::Temp');
var fh = tmpfile.new(UNLINK => 0);
say fh.filename;
fh.print("Hello, World!\n");
fh.close;

View file

@ -0,0 +1,35 @@
#!/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;

View file

@ -0,0 +1 @@
val filename = OS.FileSys.tmpName ();

View file

@ -0,0 +1,6 @@
$$ MODE TUSCRIPT
tmpfile="test.txt"
ERROR/STOP CREATE (tmpfile,seq-E,-std-)
text="hello world"
FILE $tmpfile = text
- tmpfile "test.txt" can only be accessed by one user an will be deleted upon programm termination

View file

@ -0,0 +1 @@
set chan [file tempfile filenameVar]

View file

@ -0,0 +1,13 @@
RESTOREUMASK=$(umask)
TRY=0
while :; do
TRY=$(( TRY + 1 ))
umask 0077
MYTMP=${TMPDIR:-/tmp}/$(basename $0).$$.$(date +%s).$TRY
trap "rm -fr $MYTMP" EXIT
mkdir "$MYTMP" 2>/dev/null && break
done
umask "$RESTOREUMASK"
cd "$MYTMP" || {
echo "Temporary directory failure on $MYTMP" >&2
exit 1; }

View file

@ -0,0 +1,30 @@
import "random" for Random
import "/ioutil" for File, FileUtil
import "/fmt" for Fmt
var rand = Random.new()
var createTempFile = Fn.new { |lines|
var tmp
while (true) {
// create a name which includes a random 6 digit number
tmp = "/tmp/temp%(Fmt.swrite("$06d", rand.int(1e6))).tmp"
if (!File.exists(tmp)) break
}
FileUtil.writeLines(tmp, lines)
return tmp
}
var lines = ["one", "two", "three"]
var tmp = createTempFile.call(lines)
System.print("Temporary file path: %(tmp)")
System.print("Original contents of temporary file:")
System.print(File.read(tmp))
// append some more lines
var lines2 = ["four", "five", "six"]
FileUtil.appendLines(tmp, lines2)
System.print("Updated contents of temporary file:")
System.print(File.read(tmp))
File.delete(tmp)
System.print("Temporary file deleted.")