Secure temporary file: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: Expand example to a run-able program that shows the file name and removes it)
(→‎{{header|Go}}: Explicitly close the temporary file; also actually use the file a little bit (grr.. damn recaptcha crap))
Line 127: Line 127:


=={{header|Go}}==
=={{header|Go}}==
Use <code>[https://golang.org/pkg/io/ioutil/#TempFile ioutil.TempFile]</code>
<lang go>package main
<lang go>package main


Line 141: Line 142:
log.Fatal(err)
log.Fatal(err)
}
}
defer f.Close()
// Make sure we remove the file once we're done.

// We need to make sure we remove the file
// once it is no longer needed.
defer os.Remove(f.Name())
defer os.Remove(f.Name())


// … use the file via 'f' …
// … use the file via 'f' …
fmt.Println("Using temporary file:", f.Name())
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).
}</lang>
}</lang>
{{out}}
{{out}}
<pre>
<pre>
Using temporary file: /tmp/foo054003078
Wrote and read: Using temporary file: /tmp/foo054003078
</pre>
</pre>