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


Golang File.Truncate方法代码示例

本文整理汇总了Golang中os.File.Truncate方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Truncate方法的具体用法?Golang File.Truncate怎么用?Golang File.Truncate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os.File的用法示例。


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

示例1: lockPidFile

// Locks PID file with a file lock.
// Keeps PID file open until applications exits.
func lockPidFile() (pidFile *os.File, err error) {
	var file *os.File
	file, err = os.OpenFile(
		PidFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, PidFileMask,
	)
	if err != nil {
		return
	}
	defer func() {
		// file must be open whole runtime to keep lock on itself
		if err != nil {
			file.Close()
		}
	}()

	if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
		return
	}
	var fileLen int
	fileLen, err = fmt.Fprint(file, os.Getpid())
	if err != nil {
		return
	}
	if err = file.Truncate(int64(fileLen)); err != nil {
		return
	}

	return file, err
}
开发者ID:escribano,项目名称:daemonigo,代码行数:31,代码来源:daemoni.go

示例2: fallocate

func fallocate(f *os.File, sz int64) error {
	err := syscall.Fallocate(int(f.Fd()), 0, 0, sz)
	if err == syscall.ENOTSUP {
		return f.Truncate(sz)
	}
	return err
}
开发者ID:Castcloud,项目名称:castcloud-go-server,代码行数:7,代码来源:advise_linux.go

示例3: createDataFile

func createDataFile(name string, length int64) (err error) {
	if (length & 3) != 0 {
		return fmt.Errorf("createDataFile only supports length that is a multiple of 4. Not %d", length)
	}
	var file *os.File
	file, err = os.Create(name)
	if err != nil {
		return
	}
	defer file.Close()
	err = file.Truncate(length)
	if err != nil {
		return
	}
	w := bufio.NewWriter(file)
	b := make([]byte, 4)
	for i := int64(0); i < length; i += 4 {
		b[0] = byte(i >> 24)
		b[1] = byte(i >> 16)
		b[2] = byte(i >> 8)
		b[3] = byte(i)
		_, err = w.Write(b)
		if err != nil {
			return
		}
	}
	return
}
开发者ID:Erikmitk,项目名称:Taipei-Torrent,代码行数:28,代码来源:tracker_test.go

示例4: bundleReset

func bundleReset(w *os.File, size int64) error {
	pending_offset := size - ENDSIZE
	if size == 0 {
		pending_offset = 0
	}
	offset, err := w.Seek(pending_offset, 0)
	if err != nil {
		return err
	}
	if offset != pending_offset {
		return errors.New("Failed to seek!")
	}
	err = w.Truncate(size)
	if err != nil {
		return err
	}
	if size == 0 {
		return nil
	}
	n, err := w.Write(zeroEnd)
	if err != nil || n != len(zeroEnd) {
		return errors.New("Failed to write end block")
	}
	return nil
}
开发者ID:EMSL-MSC,项目名称:pacifica-uploader-2.0,代码行数:25,代码来源:bundler.go

示例5: FindAndReplaceFd

func FindAndReplaceFd(fd *os.File, oldPattern, newPattern string) error {
	fbuf, err := ioutil.ReadAll(fd)
	if err != nil {
		return err
	}
	fd.Seek(0, -1)
	fd.Truncate(0)
	expr, err := regexp.Compile(oldPattern)
	if err != nil {
		return err
	}
	buffer := bytes.NewBuffer(fbuf)
	for {
		line, err := buffer.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		if expr.MatchString(line) {
			line = expr.ReplaceAllString(line, newPattern)
		}
		if _, err := fd.WriteString(line); err != nil {
			return err
		}
	}
	return nil
}
开发者ID:weldpua2008,项目名称:deployer,代码行数:29,代码来源:io.go

示例6: Generate_d5sFile

func Generate_d5sFile(file string, d5sConf *D5ServConf) (e error) {
	var f *os.File
	if file == NULL {
		f = os.Stdout
	} else {
		f, e = os.OpenFile(file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0600)
		ThrowErr(e)
		e = f.Truncate(0)
		ThrowErr(e)
		defer func() {
			f.Sync()
			f.Close()
		}()
	}
	if d5sConf == nil {
		d5sConf = new(D5ServConf)
		d5sConf.RSAKeys = GenerateRSAKeyPair()
	}
	desc := getImportableDesc(d5sConf)
	f.WriteString("#\n# deblocus server configuration\n#\n\n")
	for k, d := range desc {
		defaultVal := d.sType.Tag.Get("importable")
		f.WriteString(fmt.Sprintf("%-16s   %s\n", k, defaultVal))
	}
	f.WriteString("\n### Please take good care of this secret file during the server life cycle.\n")
	f.WriteString("### DON'T modify the following lines, unless you known what happens.\n\n")
	k := d5sConf.RSAKeys
	keyBytes := x509.MarshalPKCS1PrivateKey(k.priv)
	keyText := pem.EncodeToMemory(&pem.Block{
		Type:  SER_KEY_TYPE,
		Bytes: keyBytes,
	})
	f.Write(keyText)
	return
}
开发者ID:4DD8A19D69F5324F9D49D17EF78BBBCC,项目名称:deblocus,代码行数:35,代码来源:utils.go

示例7: empty

func empty(f *os.File) error {
	if err := f.Truncate(0); err != nil {
		return err
	}
	_, err := f.Seek(0, 0)
	return err
}
开发者ID:mvdan,项目名称:sh,代码行数:7,代码来源:main.go

示例8: New

func New(path string) (pf *PidFile, err error) {
	pf = &PidFile{path, os.Getpid()}
	var f *os.File
	f, err = os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
	if err != nil {
		f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
		if err != nil {
			return
		}
		var pidstr [10]byte
		var n int
		n, err = f.Read(pidstr[:])
		if err != nil {
			return
		}
		var pid int
		pid, err = strconv.Atoi(string(pidstr[:n]))
		if err != nil {
			return
		}
		_, err = os.FindProcess(pid)
		if err == nil {
			// process exists
			err = ProcessExists
			return
		}
		f.Truncate(int64(n))
	}
	defer f.Close()
	_, err = f.WriteString(strconv.Itoa(pf.Pid))
	return
}
开发者ID:newthinker,项目名称:golib,代码行数:32,代码来源:pid.go

示例9: testAccCreateZipFromFiles

func testAccCreateZipFromFiles(files map[string]string, zipFile *os.File) error {
	zipFile.Truncate(0)
	zipFile.Seek(0, 0)

	w := zip.NewWriter(zipFile)

	for source, destination := range files {
		f, err := w.Create(destination)
		if err != nil {
			return err
		}

		fileContent, err := ioutil.ReadFile(source)
		if err != nil {
			return err
		}

		_, err = f.Write(fileContent)
		if err != nil {
			return err
		}
	}

	err := w.Close()
	if err != nil {
		return err
	}

	return w.Flush()
}
开发者ID:richardbowden,项目名称:terraform,代码行数:30,代码来源:resource_aws_lambda_function_test.go

示例10: addTagsToFile

func addTagsToFile(file *os.File, tags []string) (success bool) {
	file.Seek(0, 0) // rewind to start with
	r, err := ioutil.ReadAll(io.Reader(file))
	if err != nil {
		log.Printf("ERROR: %s\n", err)
		return
	}
	loc := bytes.Index(r, gitScissorMarker)
	if loc < 0 {
		if _, err := file.Seek(0, 2); err != nil { // seek to end of file
			log.Printf("ERROR: %s\n", err)
			return
		}
	} else {
		if _, err := file.Seek(int64(loc), 0); err != nil { // seek to scissor line then truncate the file here
			log.Printf("ERROR: %s\n", err)
			return
		}
		if err := file.Truncate(int64(loc + 1)); err != nil {
			log.Printf("ERROR: %s\n", err)
			return
		}
	}
	fmt.Fprintln(file, "") // blank line first to ensure it's not stuck to the summary
	for _, tag := range tags {
		fmt.Fprintln(file, tag)
	}
	return true
}
开发者ID:GoodGuide,项目名称:gg-git-hooks,代码行数:29,代码来源:commit_msg.go

示例11: appendRegion

func appendRegion(rid int64, f *os.File, regionSizeB int64) (*region, error) {
	size, err := f.Seek(0, os.SEEK_END)
	if err != nil {
		return nil, err
	}
	if err := f.Truncate(size + regionSizeB); err != nil {
		return nil, err
	}

	// Initialize header
	header := make([]byte, regionHeaderSize)
	copy(header[:8], signature)
	*(*int64)(unsafe.Pointer(&header[regionFreePointerOffset])) = regionHeaderSize
	*(*int64)(unsafe.Pointer(&header[regionSizeOffset])) = regionSizeB
	*(*int64)(unsafe.Pointer(&header[regionId])) = rid
	if _, err := f.Write(header); err != nil {
		return nil, err
	}
	r, err := openRegion(f, true, size)
	if err != nil {
		return nil, err
	}
	r.initBlockList()
	return r, nil
}
开发者ID:alecthomas,项目名称:vheap,代码行数:25,代码来源:region.go

示例12: TorrentData

func TorrentData(md *metainfo.Info, location string) (ret *torrentData, err error) {
	var mms mmap_span.MMapSpan
	defer func() {
		if err != nil {
			mms.Close()
		}
	}()
	for _, miFile := range md.UpvertedFiles() {
		fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
		err = os.MkdirAll(filepath.Dir(fileName), 0777)
		if err != nil {
			err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
			return
		}
		var file *os.File
		file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			return
		}
		func() {
			defer file.Close()
			var fi os.FileInfo
			fi, err = file.Stat()
			if err != nil {
				return
			}
			if fi.Size() < miFile.Length {
				err = file.Truncate(miFile.Length)
				if err != nil {
					return
				}
			}
			if miFile.Length == 0 {
				// Can't mmap() regions with length 0.
				return
			}
			var mMap mmap.MMap
			mMap, err = mmap.MapRegion(file,
				int(miFile.Length), // Probably not great on <64 bit systems.
				mmap.RDWR, 0, 0)
			if err != nil {
				err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
				return
			}
			if int64(len(mMap)) != miFile.Length {
				panic("mmap has wrong length")
			}
			mms.Append(mMap)
		}()
		if err != nil {
			return
		}
	}
	ret = &torrentData{
		MMapSpan:  mms,
		completed: make([]bool, md.NumPieces()),
	}
	return
}
开发者ID:jaswinder-singh,项目名称:torrentsaga,代码行数:59,代码来源:mmap.go

示例13: touchCheckOkFile

func touchCheckOkFile(f *os.File) (err os.Error) {
	name := f.Name() + ".ok"
	f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
	if err == nil {
		f.Truncate(0)
		f.Close()
	}
	return
}
开发者ID:pjjw,项目名称:ncd,代码行数:9,代码来源:nagios.go

示例14: TorrentData

func TorrentData(md *metainfo.Info, location string) (mms *mmap_span.MMapSpan, err error) {
	mms = &mmap_span.MMapSpan{}
	defer func() {
		if err != nil {
			mms.Close()
			mms = nil
		}
	}()
	for _, miFile := range md.UpvertedFiles() {
		fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
		err = os.MkdirAll(filepath.Dir(fileName), 0777)
		if err != nil {
			err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
			return
		}
		var file *os.File
		file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			return
		}
		func() {
			defer file.Close()
			var fi os.FileInfo
			fi, err = file.Stat()
			if err != nil {
				return
			}
			if fi.Size() < miFile.Length {
				err = file.Truncate(miFile.Length)
				if err != nil {
					return
				}
			}
			if miFile.Length == 0 {
				// Can't mmap() regions with length 0.
				return
			}
			var mMap gommap.MMap
			mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
			if err != nil {
				err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
				return
			}
			if int64(len(mMap)) != miFile.Length {
				panic("mmap has wrong length")
			}
			mms.Append(mMap)
		}()
		if err != nil {
			return
		}
	}
	return
}
开发者ID:pmwoodward3,项目名称:torrentsaga,代码行数:54,代码来源:mmap.go

示例15: WriteAt

func (r *HdCache) WriteAt(p []byte, off int64) []chunk {
	boxI := int(off / int64(r.pieceSize))
	boxOff := int(off % int64(r.pieceSize))

	for i := 0; i < len(p); {
		var box *os.File
		var err error
		if !r.boxExists.IsSet(boxI) { //box doesn't exist, so we'll make one.
			box, err = os.Create(r.boxPrefix + strconv.Itoa(boxI))
			if err != nil {
				log.Panicln("Couldn't create cache file:", err)
				return nil
			}
			r.boxExists.Set(boxI)
			box.Truncate(int64(r.pieceSize))
			r.actualUsage++
		} else { //box exists, so we'll open it
			box, err = os.OpenFile(r.boxPrefix+strconv.Itoa(boxI), os.O_WRONLY, 0777)
			if err != nil {
				log.Println("Error opening cache item we thought we had:", r.boxPrefix+strconv.Itoa(boxI), "error:", err)
				r.removeBox(boxI)
				continue //loop around without incrementing 'i', forget this ever happened
			}
		}
		end := r.pieceSize - boxOff
		if len(p) < end {
			end = len(p)
		}
		copied, err := box.WriteAt(p[i:end], int64(boxOff))
		if err != nil {
			log.Panicln("Error at write cache box:", box.Name(), "error:", err)
		}
		i += copied
		box.Close()
		r.atimes[boxI] = time.Now()
		if copied == r.pieceSize {
			r.isBoxFull.Set(boxI)
		} else {
			if r.isByteSet[boxI].n == 0 {
				r.isByteSet[boxI] = *NewBitset(r.pieceSize)
			}
			for j := boxOff; j < boxOff+copied; j++ {
				r.isByteSet[boxI].Set(j)
			}
		}
		boxI++
		boxOff = 0
	}
	if r.actualUsage > r.getCapacity() {
		return r.trim()
	}
	return nil
}
开发者ID:peernode,项目名称:Taipei-Torrent,代码行数:53,代码来源:hdcache.go


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