本文整理汇总了Golang中os.File.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Close方法的具体用法?Golang File.Close怎么用?Golang File.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.File
的用法示例。
在下文中一共展示了File.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestReadSymlinkedDirectoryToFile
// Reading a symlink to a file must fail
func TestReadSymlinkedDirectoryToFile(t *testing.T) {
var err error
var file *os.File
if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil {
t.Fatalf("failed to create file: %s", err)
}
file.Close()
if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil {
t.Errorf("failed to create symlink: %s", err)
}
var path string
if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil {
t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed")
}
if path != "" {
t.Fatalf("path should've been empty: %s", path)
}
if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil {
t.Errorf("failed to remove file: %s", err)
}
if err = os.Remove("/tmp/fileLinkTest"); err != nil {
t.Errorf("failed to remove symlink: %s", err)
}
}
示例2: listenStream
func listenStream(netw, addr string) (l net.Listener, err error) {
var (
file *os.File
)
fd, err := listen(netw, addr)
if err != nil {
return nil, err
}
// Set backlog size to the maximum
if err = syscall.Listen(fd, syscall.SOMAXCONN); err != nil {
syscall.Close(fd)
return nil, err
}
file = os.NewFile(uintptr(fd), filePrefix+strconv.Itoa(os.Getpid()))
if l, err = net.FileListener(file); err != nil {
syscall.Close(fd)
return nil, err
}
if err = file.Close(); err != nil {
syscall.Close(fd)
l.Close()
return nil, err
}
return l, err
}
示例3: main
func main() {
var outFile *os.File
var err error
if outFile, err = os.Create("create.png"); err != nil {
println("Error", err)
return
}
defer outFile.Close()
rect := image.Rect(0, 0, 100, 100)
rgba := image.NewRGBA64(rect)
// #golangとか書きたいけど、とりあえず#だけ
for i := 0; i < 10; i++ {
rgba.Set(60, (10 + i), image.Black.At(0, 0))
rgba.Set(65, (10 + i), image.Black.At(0, 0))
rgba.Set((58 + i), 13, image.Black.At(0, 0))
rgba.Set((58 + i), 16, image.Black.At(0, 0))
}
outImage := rgba.SubImage(rect)
if err = png.Encode(outFile, outImage); err != nil {
println("Error", err)
return
}
}
示例4: load
func (v *Volume) load(alsoLoadIndex bool) error {
var e error
fileName := path.Join(v.dir, v.Id.String())
if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
} else if !exists || canWrite {
v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
} else if exists && canRead {
glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
v.dataFile, e = os.Open(fileName + ".dat")
v.readOnly = true
} else {
return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
}
if e != nil {
if !os.IsPermission(e) {
return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
}
}
if v.ReplicaType == CopyNil {
e = v.readSuperBlock()
} else {
e = v.maybeWriteSuperBlock()
}
if e == nil && alsoLoadIndex {
var indexFile *os.File
if v.readOnly {
glog.V(1).Infoln("open to read file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
}
if v.ensureConvertIdxToCdb(fileName) {
v.nm, e = OpenCdbMap(fileName + ".cdb")
return e
}
if indexFile != nil {
glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
} else {
indexFile.Close()
os.Remove(indexFile.Name())
indexFile = nil
}
}
} else {
glog.V(1).Infoln("open to write file", fileName+".idx")
if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
}
}
glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
if v.nm, e = LoadNeedleMap(indexFile); e != nil {
glog.V(0).Infoln("loading error:", e)
}
}
return e
}
示例5: ensureConvertIdxToCdb
func (v *Volume) ensureConvertIdxToCdb(fileName string) (cdbCanRead bool) {
var indexFile *os.File
var e error
_, cdbCanRead, cdbCanWrite, cdbModTime := checkFile(fileName + ".cdb")
_, idxCanRead, _, idxModeTime := checkFile(fileName + ".idx")
if cdbCanRead && cdbModTime.After(idxModeTime) {
return true
}
if !cdbCanWrite {
return false
}
if !idxCanRead {
glog.V(0).Infoln("Can not read file", fileName+".idx!")
return false
}
glog.V(2).Infoln("opening file", fileName+".idx")
if indexFile, e = os.Open(fileName + ".idx"); e != nil {
glog.V(0).Infoln("Failed to read file", fileName+".idx !")
return false
}
defer indexFile.Close()
glog.V(0).Infof("converting %s.idx to %s.cdb", fileName, fileName)
if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
glog.V(0).Infof("error converting %s.idx to %s.cdb: %s", fileName, fileName, e.Error())
return false
}
return true
}
示例6: main
func main() {
var file *os.File
var outFile *os.File
var img image.Image
var err error
if file, err = os.Open("pkg.png"); err != nil {
println("Error", err)
return
}
defer file.Close()
if img, err = png.Decode(file); err != nil {
println("Error", err)
return
}
if outFile, err = os.Create("out_pkg.jpeg"); err != nil {
println("Error", err)
return
}
option := &jpeg.Options{Quality: 100}
if err = jpeg.Encode(outFile, img, option); err != nil {
println()
return
}
defer outFile.Close()
}
示例7: main
func main() {
var file *os.File
var err error
if file, err = os.Open("files/sample.tar.bz2"); err != nil {
log.Fatalln(err)
}
defer file.Close()
reader := tar.NewReader(bzip2.NewReader(file))
var header *tar.Header
for {
header, err = reader.Next()
if err == io.EOF {
// ファイルの最後
break
}
if err != nil {
log.Fatalln(err)
}
buf := new(bytes.Buffer)
if _, err = io.Copy(buf, reader); err != nil {
log.Fatalln(err)
}
if err = ioutil.WriteFile("output/"+header.Name, buf.Bytes(), 0755); err != nil {
log.Fatal(err)
}
}
}
示例8: readLines
func readLines(path string) (lines []string, err error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
示例9: Save
func (f *File) Save() (err error) {
var done sync.Mutex
done.Lock()
f.cbs <- func() {
defer done.Unlock()
tmpPath := f.path + "." + strconv.FormatInt(rand.Int63(), 10)
var tmpF *os.File
tmpF, err = os.Create(tmpPath)
if err != nil {
return
}
defer tmpF.Close()
buf := new(bytes.Buffer)
err = json.NewEncoder(buf).Encode(f.Obj)
if err != nil {
return
}
// indent
indentBuf := new(bytes.Buffer)
err = json.Indent(indentBuf, buf.Bytes(), "", " ")
if err != nil {
return
}
_, err = tmpF.Write(indentBuf.Bytes())
if err != nil {
return
}
err = os.Rename(tmpPath, f.path)
if err != nil {
return
}
}
done.Lock()
return
}
示例10: Lock
// Lock creates a lockfile which prevents to open more than one instance
// of the same node (on the same machine).
func (ctx *Context) Lock() (err error) {
var f *os.File
var p *os.Process
var pid int
lockFile := path.Join(ctx.storageDir, ctx.nodeName+".lock")
if f, err = os.Open(lockFile); err != nil {
goto lock
}
if _, err = fmt.Fscanf(f, "%d", &pid); err != nil && pid == 0 {
goto lock
}
if p, err = os.FindProcess(pid); err == nil && p != nil {
if err = p.Signal(os.UnixSignal(0)); err == nil {
return errors.New(
fmt.Sprintf("node '%s' is already running",
ctx.NodeName()))
}
}
lock:
// Write a lock file.
if f, err = os.Create(lockFile); err == nil {
pid := os.Getppid()
f.Write([]byte(fmt.Sprintf("%d", pid)))
f.Close()
}
return nil
}
示例11: Fire
// Open the file, write to the file, close the file.
// Whichever user is running the function needs write permissions to the file or directory if the file does not yet exist.
func (hook *lfsHook) Fire(entry *logrus.Entry) error {
var (
fd *os.File
path string
msg string
err error
ok bool
)
if path, ok = hook.paths[entry.Level]; !ok {
err = fmt.Errorf("no file provided for loglevel: %d", entry.Level)
log.Println(err.Error())
return err
}
fd, err = os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
log.Println("failed to open logfile:", path, err)
return err
}
defer fd.Close()
msg, err = entry.String()
if err != nil {
log.Println("failed to generate string for entry:", err)
return err
}
fd.WriteString(msg)
return nil
}
示例12: persistMetaData
// persistMetaData atomically writes state to the filesystem
func (d *diskQueue) persistMetaData() error {
var f *os.File
var err error
fileName := d.metaDataFileName()
tmpFileName := fmt.Sprintf("%s.%d.tmp", fileName, rand.Int())
// write to tmp file
f, err = os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
_, err = fmt.Fprintf(f, "%d\n%d,%d\n%d,%d\n",
atomic.LoadInt64(&d.depth),
d.readFileNum, d.readPos,
d.writeFileNum, d.writePos)
if err != nil {
f.Close()
return err
}
f.Sync()
f.Close()
// atomically rename
return atomicRename(tmpFileName, fileName)
}
示例13: retrieveMetaData
// retrieveMetaData initializes state from the filesystem
func (d *diskQueue) retrieveMetaData() error {
var f *os.File
var err error
fileName := d.metaDataFileName()
f, err = os.OpenFile(fileName, os.O_RDONLY, 0600)
if err != nil {
return err
}
defer f.Close()
var depth int64
_, err = fmt.Fscanf(f, "%d\n%d,%d\n%d,%d\n",
&depth,
&d.readFileNum, &d.readPos,
&d.writeFileNum, &d.writePos)
if err != nil {
return err
}
atomic.StoreInt64(&d.depth, depth)
d.nextReadFileNum = d.readFileNum
d.nextReadPos = d.readPos
return nil
}
示例14: export
func export(file string, connection string) {
var wadokufile *os.File
var xmldata []byte
var err error
if wadokufile, err = os.Open(file); err != nil {
log.Fatal("Can't open wadoku XML file: " + err.Error())
}
defer wadokufile.Close()
if xmldata, err = ioutil.ReadAll(wadokufile); err != nil {
log.Fatal("Can't read wadoku XML file: " + err.Error())
}
dict := XMLDict{}
if err = xml.Unmarshal([]byte(xmldata), &dict); err != nil {
log.Fatal("Can't unmarshal xmldata: " + err.Error())
return
}
if err = saveIntoMongo(dict, connection); err != nil {
log.Fatal("Can't save entries into mongodb: " + err.Error())
}
}
示例15: downloadFile
func downloadFile(URL string) (fileName string, err error) {
var file *os.File
if file, err = ioutil.TempFile(os.TempDir(), "torrent-imageviewer"); err != nil {
return
}
defer func() {
if err := file.Close(); err != nil {
log.Printf("Error closing torrent file: %s", err)
}
}()
response, err := http.Get(URL)
if err != nil {
return
}
defer func() {
if err := response.Body.Close(); err != nil {
log.Printf("Error closing torrent file: %s", err)
}
}()
_, err = io.Copy(file, response.Body)
return file.Name(), err
}