Temporary files and directories sample

Followup on discussion in #243
This commit is contained in:
Eli Bendersky 2019-06-17 06:01:41 -07:00 committed by Mark McGranaghan
parent f9050decb5
commit 8219122e44
7 changed files with 307 additions and 1 deletions

View File

@ -56,6 +56,7 @@ SHA1 Hashes
Base64 Encoding
Reading Files
Writing Files
Temporary Files and Directories
Line Filters
File Paths
Directories

View File

@ -0,0 +1,65 @@
// Throughout program execution, we often want to create
// data that isn't needed after the program exits.
// *Temporary files and directories* are useful for this
// purpose since they don't pollute the file system over
// time.
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
// The easiest way to create a temporary file is by
// calling `ioutil.TempFile`. It creates a file *and*
// opens it for reading and writing. We provide `""`
// as the first argument, so `ioutil.TempFile` will
// create the file in the default location for our OS.
f, err := ioutil.TempFile("", "sample")
check(err)
// Display the name of the temporary file. On
// Unix-based OSes the directory will likely be `/tmp`.
// The file name starts with the prefix given as the
// second argument to `ioutil.TempFile` and the rest
// is chosen automatically to ensure that concurrent
// calls will always create different file names.
fmt.Println("Temp file name:", f.Name())
// Clean up the file after we're done. The OS is
// likely to clean up temporary files by itself after
// some time, but it's good practice to do this
// explicitly.
defer os.Remove(f.Name())
// We can write some data to the file.
_, err = f.Write([]byte{1, 2, 3, 4})
check(err)
// If we intend to write many temporary files, we may
// prefer to create a temporary *directory*.
// `ioutil.TempDir`'s arguments are the same as
// `TempFile`'s, but it returns a directory *name*
// rather than an open file.
dname, err := ioutil.TempDir("", "sampledir")
fmt.Println("Temp dir name:", dname)
defer os.RemoveAll(dname)
// Now we can synthesize temporary file names by
// prefixing them with our temporary directory.
fname := filepath.Join(dname, "file1")
err = ioutil.WriteFile(fname, []byte{1, 2}, 0666)
check(err)
}

View File

@ -0,0 +1,2 @@
5f7d0c43988d7dce235adb06ec02f4d2026b7f83
pxE20wGTFjv

View File

@ -0,0 +1,4 @@
# The exact names printed out will likely be different.
$ go run temporary-files-and-directories.go
Temp file name: /tmp/sample610887201
Temp dir name: /tmp/sampledir898854668

View File

@ -139,6 +139,8 @@
<li><a href="writing-files">Writing Files</a></li>
<li><a href="temporary-files-and-directories">Temporary Files and Directories</a></li>
<li><a href="line-filters">Line Filters</a></li>
<li><a href="file-paths">File Paths</a></li>

View File

@ -0,0 +1,232 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Go by Example: Temporary Files and Directories</title>
<link rel=stylesheet href="site.css">
</head>
<body>
<div class="example" id="temporary-files-and-directories">
<h2><a href="./">Go by Example</a>: Temporary Files and Directories</h2>
<table>
<tr>
<td class="docs">
<p>Throughout program execution, we often want to create
data that isn&rsquo;t needed after the program exits.
<em>Temporary files and directories</em> are useful for this
purpose since they don&rsquo;t pollute the file system over
time.</p>
</td>
<td class="code empty leading">
</td>
</tr>
<tr>
<td class="docs">
</td>
<td class="code leading">
<a href="http://play.golang.org/p/pxE20wGTFjv">
<img title="Run code" class="run" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAYAAADtc08vAAAABGdBTUEAANbY1E9YMgAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJ1SURBVCjPY/j//z8DMu7o6GAAgpQgD9tLqcmJH4KDg14aaik/MtdXe2ZjY6OCrh6Fs2jRYmZ9Pd05M9uL/u9dPfU/CLS0dfxvKIz/X5Dg/z8pKdkGqwGpqakMUdExDHJSYqt37tjxf+qUSf9rc2P+79298/+RA3v+H1zV///o6r7/DrbWFQkJiQwxMTGoBjAxMTpKiQmuqMuP/f/xw/v/J0+f/W9tbvTfxVLn/8rJVf+v757z/96hRf8TQtxuCQmLMjk4OKAawMfDVWVvrvd85eTq/7tXTP6/e/XM/22lif9LCnL+b13Q/v/Kzln/L++c/X/7/Jb/VpYWuZFRUagGAAErEBtlxvi+vn944f9L26cDNcz6v21R9/8zm6aC2SBDbu+f/78kK+4/L79AO7oBYCAqxD/57JZp/y/tmPX/wrYZ/6+CbAayD6zs/78daBjIgPayFJAGG6wGAIFAcpjH/dv7F4ANABuya/b/Od3l/ye2V/+/tnv2/7ldxSANmrgMYGBhZg7fuagD7GyYIeeBrrqwdRrQgLn/l02sBGkwwWkAEAjV5EZ/vQV0LswAGAYZsLC3DKTBAJ8BzCkRni/uHFyIYcAtoNc6ypL/ANVIohigrKwMxqqqqgxMzKzM6VHeL+6iGQAKzDtAV5XlJv3n5uFLRTHgzZs3YPzz50+GwqJiPitD9Y8Pjy4BB+CNvfP+3wUmIpAhhckhr3X19LodHZ28UQxQU1MDYw0NDQYBAQEeoBOTK7JjP2xf3Pt/bkfB/4KkoDcKMmIL5OXlFerq6hhu3rzJgC8MwMDYxGSfm5vbVn9/f0cgVxAkpqioyFBfX49iAACbTAK+xT3CzgAAAABJRU5ErkJggg==" />
</a>
<div class="highlight"><pre><span class="kn">package</span> <span class="nx">main</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
</td>
<td class="code leading">
<div class="highlight"><pre><span class="kn">import</span> <span class="p">(</span>
<span class="s">&quot;fmt&quot;</span>
<span class="s">&quot;io/ioutil&quot;</span>
<span class="s">&quot;os&quot;</span>
<span class="s">&quot;path/filepath&quot;</span>
<span class="p">)</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
</td>
<td class="code leading">
<div class="highlight"><pre><span class="kd">func</span> <span class="nx">check</span><span class="p">(</span><span class="nx">e</span> <span class="kt">error</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="nx">e</span> <span class="o">!=</span> <span class="kc">nil</span> <span class="p">{</span>
<span class="nb">panic</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
</td>
<td class="code leading">
<div class="highlight"><pre><span class="kd">func</span> <span class="nx">main</span><span class="p">()</span> <span class="p">{</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>The easiest way to create a temporary file is by
calling <code>ioutil.TempFile</code>. It creates a file <em>and</em>
opens it for reading and writing. We provide <code>&quot;&quot;</code>
as the first argument, so <code>ioutil.TempFile</code> will
create the file in the default location for our OS.</p>
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="nx">f</span><span class="p">,</span> <span class="nx">err</span> <span class="o">:=</span> <span class="nx">ioutil</span><span class="p">.</span><span class="nx">TempFile</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">,</span> <span class="s">&quot;sample&quot;</span><span class="p">)</span>
<span class="nx">check</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>Display the name of the temporary file. On
Unix-based OSes the directory will likely be <code>/tmp</code>.
The file name starts with the prefix given as the
second argument to <code>ioutil.TempFile</code> and the rest
is chosen automatically to ensure that concurrent
calls will always create different file names.</p>
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;Temp file name:&quot;</span><span class="p">,</span> <span class="nx">f</span><span class="p">.</span><span class="nx">Name</span><span class="p">())</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>Clean up the file after we&rsquo;re done. The OS is
likely to clean up temporary files by itself after
some time, but it&rsquo;s good practice to do this
explicitly.</p>
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="k">defer</span> <span class="nx">os</span><span class="p">.</span><span class="nx">Remove</span><span class="p">(</span><span class="nx">f</span><span class="p">.</span><span class="nx">Name</span><span class="p">())</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>We can write some data to the file.</p>
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="nx">_</span><span class="p">,</span> <span class="nx">err</span> <span class="p">=</span> <span class="nx">f</span><span class="p">.</span><span class="nx">Write</span><span class="p">([]</span><span class="kt">byte</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">})</span>
<span class="nx">check</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>If we intend to write many temporary files, we may
prefer to create a temporary <em>directory</em>.
<code>ioutil.TempDir</code>&rsquo;s arguments are the same as
<code>TempFile</code>&rsquo;s, but it returns a directory <em>name</em>
rather than an open file.</p>
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="nx">dname</span><span class="p">,</span> <span class="nx">err</span> <span class="o">:=</span> <span class="nx">ioutil</span><span class="p">.</span><span class="nx">TempDir</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">,</span> <span class="s">&quot;sampledir&quot;</span><span class="p">)</span>
<span class="nx">fmt</span><span class="p">.</span><span class="nx">Println</span><span class="p">(</span><span class="s">&quot;Temp dir name:&quot;</span><span class="p">,</span> <span class="nx">dname</span><span class="p">)</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
</td>
<td class="code leading">
<div class="highlight"><pre> <span class="k">defer</span> <span class="nx">os</span><span class="p">.</span><span class="nx">RemoveAll</span><span class="p">(</span><span class="nx">dname</span><span class="p">)</span>
</pre></div>
</td>
</tr>
<tr>
<td class="docs">
<p>Now we can synthesize temporary file names by
prefixing them with our temporary directory.</p>
</td>
<td class="code">
<div class="highlight"><pre> <span class="nx">fname</span> <span class="o">:=</span> <span class="nx">filepath</span><span class="p">.</span><span class="nx">Join</span><span class="p">(</span><span class="nx">dname</span><span class="p">,</span> <span class="s">&quot;file1&quot;</span><span class="p">)</span>
<span class="nx">err</span> <span class="p">=</span> <span class="nx">ioutil</span><span class="p">.</span><span class="nx">WriteFile</span><span class="p">(</span><span class="nx">fname</span><span class="p">,</span> <span class="p">[]</span><span class="kt">byte</span><span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">},</span> <span class="mo">0666</span><span class="p">)</span>
<span class="nx">check</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span>
<span class="p">}</span>
</pre></div>
</td>
</tr>
</table>
<table>
<tr>
<td class="docs">
<p>The exact names printed out will likely be different.</p>
</td>
<td class="code">
<div class="highlight"><pre><span class="gp">$</span> go run temporary-files-and-directories.go
<span class="go">Temp file name: /tmp/sample610887201</span>
<span class="go">Temp dir name: /tmp/sampledir898854668</span>
</pre></div>
</td>
</tr>
</table>
<p class="next">
Next example: <a href="line-filters">Line Filters</a>.
</p>
<p class="footer">
by <a href="https://markmcgranaghan.com">Mark McGranaghan</a> | <a href="https://github.com/mmcgrana/gobyexample/blob/master/examples/temporary-files-and-directories">source</a> | <a href="https://github.com/mmcgrana/gobyexample#license">license</a>
</p>
</div>
</body>
</html>

View File

@ -266,7 +266,7 @@ we&rsquo;ve just seen to the <code>stdin</code> and <code>stdout</code> streams.
<p class="next">
Next example: <a href="line-filters">Line Filters</a>.
Next example: <a href="temporary-files-and-directories">Temporary Files and Directories</a>.
</p>
<p class="footer">