github.com/scaleoutsean/fusego@v0.0.0-20220224074057-4a6429e46bb8/fsutil/fsutil.go (about) 1 // Copyright 2015 Google Inc. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package fsutil 16 17 import ( 18 "fmt" 19 "io/ioutil" 20 "os" 21 "path" 22 ) 23 24 // Create a temporary file with the same semantics as ioutil.TempFile, but 25 // ensure that it is unlinked before returning so that it does not persist 26 // after the process exits. 27 // 28 // Warning: this is not production-quality code, and should only be used for 29 // testing purposes. In particular, there is a race between creating and 30 // unlinking by name. 31 func AnonymousFile(dir string) (*os.File, error) { 32 // Choose a prefix based on the binary name. 33 prefix := path.Base(os.Args[0]) 34 35 // Create the file. 36 f, err := ioutil.TempFile(dir, prefix) 37 if err != nil { 38 return nil, fmt.Errorf("TempFile: %v", err) 39 } 40 41 // Unlink it. 42 if err := os.Remove(f.Name()); err != nil { 43 return nil, fmt.Errorf("Remove: %v", err) 44 } 45 46 return f, nil 47 } 48 49 // Call fdatasync on the supplied file. 50 // 51 // REQUIRES: FdatasyncSupported is true. 52 func Fdatasync(f *os.File) error { 53 return fdatasync(f) 54 }