当前位置: 首页>>代码示例>>Golang>>正文


Golang os.OpenFile函数代码示例

本文整理汇总了Golang中os.OpenFile函数的典型用法代码示例。如果您正苦于以下问题:Golang OpenFile函数的具体用法?Golang OpenFile怎么用?Golang OpenFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了OpenFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewLogger

// NewLogger creates a new logger
func NewLogger(stdout string, stderr string) (logger *Logger, err error) {
	var (
		stderrWriter = os.Stderr
		stdoutWriter = os.Stdout
		toClose      []closeable
	)

	if stderr != "" {
		if stderrWriter, err = os.OpenFile(stderr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
			return
		}
		toClose = append(toClose, stderrWriter)
	}
	if stdout != "" {
		if stdoutWriter, err = os.OpenFile(stdout, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
			return
		}
		toClose = append(toClose, stderrWriter)
	}

	logger = &Logger{
		stderr:  log.New(stderrWriter, "ERROR ", log.LstdFlags|log.Lshortfile),
		stdout:  log.New(stdoutWriter, "INFO ", log.LstdFlags|log.Lshortfile),
		toClose: toClose,
	}
	return
}
开发者ID:bradparks,项目名称:flashback,代码行数:28,代码来源:logger.go

示例2: benchmarkBTreeSetACIDFiler

func benchmarkBTreeSetACIDFiler(b *testing.B, sz int) {
	dir, testDbName := temp()
	defer os.RemoveAll(dir)

	f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer f.Close()

	wal, err := os.OpenFile(testDbName+".wal", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer wal.Close()

	filer, err := NewACIDFiler(NewSimpleFileFiler(f), wal)
	if err != nil {
		b.Error(err)
		return
	}

	benchmarkBTreeSetFiler(b, filer, sz)
}
开发者ID:camarox53,项目名称:coreos-baremetal,代码行数:26,代码来源:btree_test.go

示例3: OpenForReading

func (node *Node) OpenForReading() (*os.File, error) {
	file, err := os.OpenFile(node.path, os.O_RDONLY|syscall.O_NOATIME, 0)
	if os.IsPermission(err) {
		return os.OpenFile(node.path, os.O_RDONLY, 0)
	}
	return file, err
}
开发者ID:rawtaz,项目名称:restic,代码行数:7,代码来源:node_linux.go

示例4: initDebugLogger

func initDebugLogger() {
	debugfile := os.Getenv("DEBUG_LOG")
	if debugfile == "" {
		return
	}

	fmt.Fprintf(os.Stderr, "debug log file %v\n", debugfile)

	f, err := os.OpenFile(debugfile, os.O_WRONLY|os.O_APPEND, 0600)

	if err == nil {
		_, err = f.Seek(2, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "unable to seek to the end of %v: %v\n", debugfile, err)
			os.Exit(3)
		}
	}

	if err != nil && os.IsNotExist(err) {
		f, err = os.OpenFile(debugfile, os.O_WRONLY|os.O_CREATE, 0600)
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "unable to open debug log file: %v\n", err)
		os.Exit(2)
	}

	opts.logger = log.New(f, "", log.LstdFlags)
}
开发者ID:marete,项目名称:restic,代码行数:29,代码来源:debug.go

示例5: 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
}
开发者ID:tgulacsi,项目名称:weed-fs,代码行数:60,代码来源:volume.go

示例6: WriteTo

// WriteTo writes the entire database to a writer.
// If err == nil then exactly tx.Size() bytes will be written into the writer.
func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
	// Attempt to open reader directly.
	var f *os.File
	if f, err = os.OpenFile(tx.db.path, os.O_RDONLY|odirect, 0); err != nil {
		// Fallback to a regular open if that doesn't work.
		if f, err = os.OpenFile(tx.db.path, os.O_RDONLY, 0); err != nil {
			return 0, err
		}
	}

	// Copy the meta pages.
	tx.db.metalock.Lock()
	n, err = io.CopyN(w, f, int64(tx.db.pageSize*2))
	tx.db.metalock.Unlock()
	if err != nil {
		_ = f.Close()
		return n, fmt.Errorf("meta copy: %s", err)
	}

	// Copy data pages.
	wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
	n += wn
	if err != nil {
		_ = f.Close()
		return n, err
	}

	return n, f.Close()
}
开发者ID:Rjaylyn,项目名称:lfs-server-go,代码行数:31,代码来源:tx.go

示例7: TestFStatFs

func TestFStatFs(t *testing.T) {
	ts := NewTestCase(t)
	defer ts.Cleanup()

	fOrig, err := os.OpenFile(ts.orig+"/file", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
	if err != nil {
		t.Fatalf("OpenFile failed: %v", err)
	}
	defer fOrig.Close()

	empty := syscall.Statfs_t{}
	s1 := empty
	errno := syscall.Fstatfs(int(fOrig.Fd()), &s1)
	if errno != nil {
		t.Fatal("statfs orig", err)
	}

	fMnt, err := os.OpenFile(ts.mnt+"/file", os.O_RDWR, 0644)
	if err != nil {
		t.Fatalf("OpenFile failed: %v", err)
	}
	defer fMnt.Close()
	s2 := empty

	errno = syscall.Fstatfs(int(fMnt.Fd()), &s2)
	if errno != nil {
		t.Fatal("statfs mnt", err)
	}

	clearStatfs(&s1)
	clearStatfs(&s2)
	if fmt.Sprintf("%v", s2) != fmt.Sprintf("%v", s1) {
		t.Errorf("statfs mismatch: %#v != %#v", s1, s2)
	}
}
开发者ID:seacoastboy,项目名称:go-fuse,代码行数:35,代码来源:loopback_test.go

示例8: openFileAndCheckpoint

// openFileAndCehckpoint will create a checkpoint file, open a new file for
// writing a data index, write the header and return the file
func (e *Engine) openFileAndCheckpoint(fileName string) (*os.File, error) {
	checkpointFile := fmt.Sprintf("%s.%s", fileName, CheckpointExtension)
	cf, err := os.OpenFile(checkpointFile, os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}
	// _, err = cf.Write(u32tob(magicNumber))
	// if err != nil {
	// 	panic(err)
	// }
	if err := cf.Close(); err != nil {
		return nil, err
	}
	_, err = os.Stat(checkpointFile)

	f, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return nil, err
	}

	// write the header, which is just the magic number
	if _, err := f.Write(u32tob(magicNumber)); err != nil {
		f.Close()
		return nil, err
	}

	return f, nil
}
开发者ID:nrshrivatsan,项目名称:influxdb,代码行数:30,代码来源:tsm1.go

示例9: benchmarkAllocatorRndGetACIDFiler

func benchmarkAllocatorRndGetACIDFiler(b *testing.B, sz int) {
	os.Remove(testDbName)
	os.Remove(walName)
	f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer func() {
		f.Close()
		os.Remove(testDbName)
	}()

	wal, err := os.OpenFile(walName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer func() {
		wal.Close()
		os.Remove(walName)
	}()

	filer, err := NewACIDFiler(NewSimpleFileFiler(f), wal)
	if err != nil {
		b.Error(err)
		return
	}

	benchmarkAllocatorRndGet(b, filer, sz)
}
开发者ID:devick,项目名称:flynn,代码行数:31,代码来源:falloc_test.go

示例10: ReloadLogger

func ReloadLogger(tutumLogFile string, dockerLogFile string) {
	if TutumLogDescriptor.Fd() != os.Stdout.Fd() {
		f, err := os.OpenFile(tutumLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			SendError(err, "Failed to open tutum log file", nil)
			log.Println(err)
			log.Println("Log to stdout instead")
			f = os.Stdout
		}
		Logger = log.New(f, "", log.Ldate|log.Ltime)
		TutumLogDescriptor.Close()
		TutumLogDescriptor = f
		Logger.Print("SIGHUP: Tutum log file descriptor has been reloaded")
	} else {
		Logger.Print("SIGHUP: No need to reload tutum logs when printing to stdout")
	}

	Logger.Print("SIGHUP: Reloading docker log file descriptor")
	f, err := os.OpenFile(dockerLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		SendError(err, "Failed to set docker log file", nil)
		Logger.Println(err)
		Logger.Println("Cannot set docker log to", dockerLogFile)
	} else {
		go io.Copy(f, DockerLogStdoutDescriptor)
		go io.Copy(f, DockerLogStderrDescriptor)
		DockerLogDescriptor.Close()
		DockerLogDescriptor = f
		Logger.Print("SIGHUP: Docker log file descriptor has been reloaded")
	}
}
开发者ID:CloudSide,项目名称:tutum-agent,代码行数:31,代码来源:config.go

示例11: Write

func (n NetworkLinks) Write(path string, appends bool) error {
	var file *os.File
	var err error

	if appends {
		file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0660)
	} else {
		file, err = os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
		if os.IsExist(err) {
			file, err = os.OpenFile(path, os.O_TRUNC|os.O_WRONLY, 0660)
		}
	}
	if err != nil {
		log.Print("network_links: Unable to open network links file: ", err)
		return err
	}
	defer file.Close()

	for i := range n {
		if _, errw := fmt.Fprintf(file, "%s\t%d\t%d\t%s\n", n[i].FromHost, n[i].FromPort, n[i].ToPort, n[i].ToHost); errw != nil {
			log.Print("network_links: Unable to write network links: ", err)
			return err
		}
	}
	if errc := file.Close(); errc != nil {
		log.Print("network_links: Unable to network links: ", errc)
		return err
	}
	return nil
}
开发者ID:roacobb,项目名称:geard,代码行数:30,代码来源:network_links.go

示例12: load

func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool) error {
	var e error
	fileName := v.FileName()

	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists {
		if !canRead {
			return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
		}
		if canWrite {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
			v.dataFile, e = os.Open(fileName + ".dat")
			v.readOnly = true
		}
	} else {
		if createDatIfMissing {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
		}
	}

	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaPlacement == nil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		if v.readOnly {
			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
		}
		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 Index %s.idx: %s", fileName, e.Error())
			}
		} 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 Index %s.idx: %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
}
开发者ID:yonglehou,项目名称:weedfs,代码行数:60,代码来源:volume.go

示例13: Configure

func Configure(fileName string, appendFile bool) error {
	StripPackage = true
	PadLocation = false
	HideLocation = false

	if len(fileName) > 0 {
		fh, e := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
		if e != nil {
			if appendFile {
				fh, e = os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0660)
			} else {
				e = os.Rename(fileName, fileName+time.Now().Format(".20060102-150405"))
				fh, e = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
			}
		}
		if e != nil {
			return e
		}
		fileHandle = fh
		writer = io.MultiWriter(fh, os.Stdout)
	} else {
		writer = os.Stdout
	}
	golog.SetFlags(golog.Ltime)
	golog.SetOutput(writer)
	maxLevel = Info
	return nil
}
开发者ID:Jeraimee,项目名称:helpers,代码行数:28,代码来源:log.go

示例14: openIo

func (c *containerProcess) openIo() (err error) {
	defer func() {
		if err != nil {
			c.Cleanup()
		}
	}()

	c.io.stdinf, err = os.OpenFile(c.io.stdin, os.O_RDWR, 0)
	if err != nil {
		return err
	}

	c.io.stdoutf, err = os.OpenFile(c.io.stdout, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	go io.Copy(&c.io.stdoutBuffer, c.io.stdoutf)

	c.io.stderrf, err = os.OpenFile(c.io.stderr, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	go io.Copy(&c.io.stderrBuffer, c.io.stderrf)

	return nil
}
开发者ID:carriercomm,项目名称:containerd,代码行数:26,代码来源:container_utils_test.go

示例15: OutputRes

func OutputRes() {
	//save all result
	allFile, err := os.OpenFile(*saveFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		logger.Println("Open file error,", err)
	}
	defer allFile.Close()

	//save has result
	hasFile, err := os.OpenFile(*hasFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		logger.Println("Open file error,", err)
	}
	defer hasFile.Close()

	var num int64 = 0
	var has int64 = 0
	for k, address := range Visit {
		str := fmt.Sprintf("%-4d has: %-5t,  url:  %s\n", num, address.Has, k)
		// logger.Printf("%-4d  has: %t,url: %-40s\n", num, address.Has, k)
		logger.Printf(str)
		allFile.WriteString(str)
		if address.Has {
			hasFile.WriteString(fmt.Sprintf("%-4d has: %-5t,  url:  %s\n", has, address.Has, k))
		}
		num++
		has++
	}
}
开发者ID:qwding,项目名称:go_distributed_spider,代码行数:29,代码来源:oneThread.go


注:本文中的os.OpenFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。