當前位置: 首頁>>代碼示例>>Golang>>正文


Golang os.File類代碼示例

本文整理匯總了Golang中os.File的典型用法代碼示例。如果您正苦於以下問題:Golang File類的具體用法?Golang File怎麽用?Golang File使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了File類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: sendTTYToCommand

func sendTTYToCommand(commandUsock *unixsocket.Usock, clientFile *os.File, err error) error {
	if err != nil {
		return err
	}

	return commandUsock.WriteFD(int(clientFile.Fd()))
}
開發者ID:honkfestival,項目名稱:zeus,代碼行數:7,代碼來源:clienthandler.go

示例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
}
開發者ID:djbarber,項目名稱:ipfs-hack,代碼行數:30,代碼來源:impl_unix.go

示例3: getTarFileBytes

func getTarFileBytes(file *os.File, path string) ([]byte, error) {
	_, err := file.Seek(0, 0)
	if err != nil {
		fmt.Errorf("error seeking file: %v", err)
	}

	var fileBytes []byte
	fileWalker := func(t *tarball.TarFile) error {
		if filepath.Clean(t.Name()) == path {
			fileBytes, err = ioutil.ReadAll(t.TarStream)
			if err != nil {
				return err
			}
		}

		return nil
	}

	tr := tar.NewReader(file)
	if err := tarball.Walk(*tr, fileWalker); err != nil {
		return nil, err
	}

	if fileBytes == nil {
		return nil, fmt.Errorf("file %q not found", path)
	}

	return fileBytes, nil
}
開發者ID:rtrentin73,項目名稱:docker2aci,代碼行數:29,代碼來源:file.go

示例4: setFileLock

func setFileLock(f *os.File, lock bool) error {
	how := syscall.LOCK_UN
	if lock {
		how = syscall.LOCK_EX
	}
	return syscall.Flock(int(f.Fd()), how|syscall.LOCK_NB)
}
開發者ID:Blueprint-Marketing,項目名稱:syncthing,代碼行數:7,代碼來源:file_storage_unix.go

示例5: 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
	}

}
開發者ID:qt-luigi,項目名稱:golangcafe,代碼行數:30,代碼來源:createpng.go

示例6: dirList

func dirList(w http.ResponseWriter, f *os.File) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if dirs, err := f.Readdir(-1); err == nil {
		files := make([]map[string]string, len(dirs)+1)
		files[0] = map[string]string{
			"name": "..", "href": "..", "size": "-", "mtime": "-",
		}
		for i, d := range dirs {
			href := d.Name()
			if d.IsDir() {
				href += "/"
			}
			files[i+1] = map[string]string{
				"name":  d.Name(),
				"href":  href,
				"size":  formatSize(d),
				"mtime": d.ModTime().Format("2006-01-02 15:04:05"),
			}
		}
		reloadCfg.dirListTmpl.Execute(w, map[string]interface{}{
			"dir":   f.Name(),
			"files": files,
		})
	}
}
開發者ID:jayvansantos,項目名稱:http-watcher,代碼行數:25,代碼來源:http-watcher.go

示例7: 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)
	}
}
開發者ID:idvoretskyi,項目名稱:coreos-kubernetes,代碼行數:32,代碼來源:utils_test.go

示例8: 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)
		}
	}
}
開發者ID:qt-luigi,項目名稱:golangcafe,代碼行數:32,代碼來源:tarbzip.go

示例9: doHandleFileConcurrently

func doHandleFileConcurrently(file *os.File, targetFolder string, handler FileHandlerForLineInFile) {
	reader := bufio.NewReader(file)
	scanner := bufio.NewScanner(reader)
	var syncStructure []chan bool

	defer file.Close()
	startTime := time.Now()
	for scanner.Scan() {
		c := make(chan bool)
		syncStructure = append(syncStructure, c)
		filenameToBeCopied := scanner.Text()
		go func() {
			doHandle(filenameToBeCopied, targetFolder, handler, c)
		}()
	}

	count := len(syncStructure)
	for i := 0; i < count; i++ {
		<-syncStructure[i]
	}

	endTime := time.Now()

	duration := endTime.Sub(startTime)
	log.Println("Time taken: " + duration.String())
}
開發者ID:abhi42,項目名稱:fileutil,代碼行數:26,代碼來源:mybackup.go

示例10: UploadReleaseAsset

// UploadReleaseAsset creates an asset by uploading a file into a release repository.
// To upload assets that cannot be represented by an os.File, call NewUploadRequest directly.
//
// GitHub API docs : http://developer.github.com/v3/repos/releases/#upload-a-release-asset
func (s *RepositoriesService) UploadReleaseAsset(owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) {
	u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id)
	u, err := addOptions(u, opt)
	if err != nil {
		return nil, nil, err
	}

	stat, err := file.Stat()
	if err != nil {
		return nil, nil, err
	}
	if stat.IsDir() {
		return nil, nil, errors.New("the asset to upload can't be a directory")
	}

	mediaType := mime.TypeByExtension(filepath.Ext(file.Name()))
	req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType)
	if err != nil {
		return nil, nil, err
	}

	asset := new(ReleaseAsset)
	resp, err := s.client.Do(req, asset)
	if err != nil {
		return nil, resp, err
	}
	return asset, resp, err
}
開發者ID:quixoten,項目名稱:vault,代碼行數:32,代碼來源:repos_releases.go

示例11: 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

示例12: 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
}
開發者ID:tgulacsi,項目名稱:weed-fs,代碼行數:28,代碼來源:volume.go

示例13: FindLoopDeviceFor

// FindLoopDeviceFor returns a loopback device file for the specified file which
// is backing file of a loop back device.
func FindLoopDeviceFor(file *os.File) *os.File {
	stat, err := file.Stat()
	if err != nil {
		return nil
	}
	targetInode := stat.Sys().(*syscall.Stat_t).Ino
	targetDevice := stat.Sys().(*syscall.Stat_t).Dev

	for i := 0; true; i++ {
		path := fmt.Sprintf("/dev/loop%d", i)

		file, err := os.OpenFile(path, os.O_RDWR, 0)
		if err != nil {
			if os.IsNotExist(err) {
				return nil
			}

			// Ignore all errors until the first not-exist
			// we want to continue looking for the file
			continue
		}

		dev, inode, err := getLoopbackBackingFile(file)
		if err == nil && dev == targetDevice && inode == targetInode {
			return file
		}
		file.Close()
	}

	return nil
}
開發者ID:CadeLaRen,項目名稱:docker-3,代碼行數:33,代碼來源:loopback.go

示例14: SetCapacity

// SetCapacity reloads the size for the loopback device.
func SetCapacity(file *os.File) error {
	if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil {
		logrus.Errorf("Error loopbackSetCapacity: %s", err)
		return ErrSetCapacity
	}
	return nil
}
開發者ID:CadeLaRen,項目名稱:docker-3,代碼行數:8,代碼來源:loopback.go

示例15: copyPathToPath

func copyPathToPath(fromPath, toPath string) (err error) {
	srcFileInfo, err := os.Stat(fromPath)
	if err != nil {
		return
	}

	if srcFileInfo.IsDir() {
		err = os.MkdirAll(toPath, srcFileInfo.Mode())
		if err != nil {
			return
		}
	} else {
		var dst *os.File
		dst, err = fileutils.Create(toPath)
		if err != nil {
			return
		}
		defer dst.Close()

		dst.Chmod(srcFileInfo.Mode())

		err = fileutils.CopyPathToWriter(fromPath, dst)
	}
	return err
}
開發者ID:Jack1996,項目名稱:cli,代碼行數:25,代碼來源:app_files.go


注:本文中的os.File類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。