]> git.ipfire.org Git - thirdparty/gcc.git/blob - libgo/go/io/ioutil/tempfile.go
Add Go frontend, libgo library, and Go testsuite.
[thirdparty/gcc.git] / libgo / go / io / ioutil / tempfile.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ioutil
6
7 import (
8 "os"
9 "strconv"
10 )
11
12 // Random number state, accessed without lock; racy but harmless.
13 // We generate random temporary file names so that there's a good
14 // chance the file doesn't exist yet - keeps the number of tries in
15 // TempFile to a minimum.
16 var rand uint32
17
18 func reseed() uint32 {
19 sec, nsec, _ := os.Time()
20 return uint32(sec*1e9 + nsec + int64(os.Getpid()))
21 }
22
23 func nextSuffix() string {
24 r := rand
25 if r == 0 {
26 r = reseed()
27 }
28 r = r*1664525 + 1013904223 // constants from Numerical Recipes
29 rand = r
30 return strconv.Itoa(int(1e9 + r%1e9))[1:]
31 }
32
33 // TempFile creates a new temporary file in the directory dir
34 // with a name beginning with prefix, opens the file for reading
35 // and writing, and returns the resulting *os.File.
36 // If dir is the empty string, TempFile uses the default directory
37 // for temporary files (see os.TempDir).
38 // Multiple programs calling TempFile simultaneously
39 // will not choose the same file. The caller can use f.Name()
40 // to find the name of the file. It is the caller's responsibility to
41 // remove the file when no longer needed.
42 func TempFile(dir, prefix string) (f *os.File, err os.Error) {
43 if dir == "" {
44 dir = os.TempDir()
45 }
46
47 nconflict := 0
48 for i := 0; i < 10000; i++ {
49 name := dir + "/" + prefix + nextSuffix()
50 f, err = os.Open(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
51 if pe, ok := err.(*os.PathError); ok && pe.Error == os.EEXIST {
52 if nconflict++; nconflict > 10 {
53 rand = reseed()
54 }
55 continue
56 }
57 break
58 }
59 return
60 }