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


Golang syscall.Rename函数代码示例

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


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

示例1: rename

func rename(oldname, newname string) error {
	e := syscall.Rename(oldname, newname)
	if e != nil {
		return &LinkError{"rename", oldname, newname, e}
	}
	return nil
}
开发者ID:kuangchanglang,项目名称:go,代码行数:7,代码来源:file_unix.go

示例2: movePkg

func movePkg(pkg *archPkg) os.Error {
	filename := fmt.Sprintf("%s-%s-%s.%s", pkg.Name, pkg.Version, pkg.Arch, pkg.Ext)
	srcPath := fmt.Sprintf("%s/%s", *cachePath, filename)

	/* try to rename, first */
	errno := syscall.Rename(srcPath, fmt.Sprintf("%s/%s", *destPath, filename))

	switch errno {
	case syscall.EXDEV:
		src, err := os.Open(srcPath, os.O_RDONLY, 0666)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err.String())
			os.Exit(1)
		}
		defer src.Close()

		sfi, err := src.Stat()

		dst, err := os.Open(fmt.Sprintf("%s/%s", *destPath, filename), os.O_WRONLY|os.O_CREAT|os.O_TRUNC, sfi.Permission())
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err.String())
			os.Exit(1)
		}
		defer dst.Close()

		err = copyFile(src, bufio.NewWriter(dst))
		if err == nil {
			return os.Remove(srcPath)
		}
		return err /* different from err outside if */
	}

	return os.Errno(errno)
}
开发者ID:falconindy,项目名称:gobble,代码行数:34,代码来源:gobble.go

示例3: ObjDeleteHandler

func ObjDeleteHandler(writer http.ResponseWriter, request *http.Request, vars map[string]string, config ServerConfig) {
	hash_dir := ObjHashDir(vars, config)

	if os.MkdirAll(hash_dir, 0770) != nil {
		ErrorResponse(writer, 500)
		return
	}
	file_name := fmt.Sprintf("%s/%s.ts", hash_dir, request.Header.Get("X-Timestamp"))
	data_file := PrimaryFile(hash_dir)
	temp_file, err := ioutil.TempFile(ObjTempDir(vars, config), "PUT")
	if err != nil {
		ErrorResponse(writer, 500)
		return
	}
	defer temp_file.Close()
	metadata := make(map[string]interface{})
	metadata["X-Timestamp"] = request.Header.Get("X-Timestamp")
	metadata["name"] = fmt.Sprintf("/%s/%s/%s", vars["account"], vars["container"], vars["obj"])
	WriteMetadata(int(temp_file.Fd()), metadata)

	syscall.Fsync(int(temp_file.Fd()))
	syscall.Rename(temp_file.Name(), file_name)
	UpdateContainer("DELETE", metadata, request, vars)
	go CleanupHashDir(hash_dir)
	go InvalidateHash(hash_dir)
	if !strings.HasSuffix(data_file, ".data") {
		ErrorResponse(writer, 404)
	} else {
		ErrorResponse(writer, 204)
	}
}
开发者ID:pandemicsyn,项目名称:bertin,代码行数:31,代码来源:main.go

示例4: Renameat

// Poor man's Renameat
func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) {
	chdirMutex.Lock()
	defer chdirMutex.Unlock()
	// Unless both paths are absolute we have to save the old working dir and
	// Chdir(oldWd) back to it in the end. If we error out before the first
	// chdir, Chdir(oldWd) is unneccassary but does no harm.
	if !filepath.IsAbs(oldpath) || !filepath.IsAbs(newpath) {
		oldWd, err := os.Getwd()
		if err != nil {
			return err
		}
		defer os.Chdir(oldWd)
	}
	// Make oldpath absolute
	oldpath, err = dirfdAbs(olddirfd, oldpath)
	if err != nil {
		return err
	}
	// Make newpath absolute
	newpath, err = dirfdAbs(newdirfd, newpath)
	if err != nil {
		return err
	}
	return syscall.Rename(oldpath, newpath)
}
开发者ID:rfjakob,项目名称:gocryptfs,代码行数:26,代码来源:sys_darwin.go

示例5: Rename

// Rename renames a file.
func Rename(oldname, newname string) Error {
	e := syscall.Rename(oldname, newname)
	if e != 0 {
		return &LinkError{"rename", oldname, newname, Errno(e)}
	}
	return nil
}
开发者ID:lougxing,项目名称:golang-china,代码行数:8,代码来源:file.go

示例6: rename

func rename(oldname, newname string) error {
	fi, err := Lstat(newname)
	if err == nil && fi.IsDir() {
		return &LinkError{"rename", oldname, newname, syscall.EEXIST}
	}
	e := syscall.Rename(oldname, newname)
	if e != nil {
		return &LinkError{"rename", oldname, newname, e}
	}
	return nil
}
开发者ID:achanda,项目名称:go,代码行数:11,代码来源:file_unix.go

示例7: ObjPutHandler

func ObjPutHandler(writer http.ResponseWriter, request *http.Request, vars map[string]string, config ServerConfig) {
	out_headers := writer.Header()
	hash_dir := ObjHashDir(vars, config)

	if os.MkdirAll(hash_dir, 0770) != nil || os.MkdirAll(ObjTempDir(vars, config), 0770) != nil {
		ErrorResponse(writer, 500)
		return
	}
	file_name := fmt.Sprintf("%s/%s.data", hash_dir, request.Header.Get("X-Timestamp"))
	temp_file, err := ioutil.TempFile(ObjTempDir(vars, config), "PUT")
	if err != nil {
		ErrorResponse(writer, 500)
		return
	}
	defer temp_file.Close()
	metadata := make(map[string]interface{})
	metadata["name"] = fmt.Sprintf("/%s/%s/%s", vars["account"], vars["container"], vars["obj"])
	metadata["X-Timestamp"] = request.Header.Get("X-Timestamp")
	metadata["Content-Type"] = request.Header.Get("Content-Type")
	var chunk [65536]byte
	total_size := uint64(0)
	hash := md5.New()
	for {
		read_len, err := request.Body.Read(chunk[0:len(chunk)])
		if err != nil || read_len <= 0 {
			break
		}
		total_size += uint64(read_len)
		hash.Write(chunk[0:read_len])
		temp_file.Write(chunk[0:read_len])
	}
	metadata["Content-Length"] = strconv.FormatUint(total_size, 10)
	metadata["ETag"] = fmt.Sprintf("%x", hash.Sum(nil))
	request_etag := request.Header.Get("ETag")
	if request_etag != "" && request_etag != metadata["ETag"].(string) {
		ErrorResponse(writer, 422)
		return
	}
	for key := range request.Header {
		if strings.HasPrefix(key, "X-Object-") {
			metadata[key] = request.Header.Get(key)
		}
	}
	out_headers.Set("ETag", metadata["ETag"].(string))
	WriteMetadata(int(temp_file.Fd()), metadata)

	syscall.Fsync(int(temp_file.Fd()))
	syscall.Rename(temp_file.Name(), file_name)
	UpdateContainer("PUT", metadata, request, vars)
	go CleanupHashDir(hash_dir)
	go InvalidateHash(hash_dir)
	ErrorResponse(writer, 201)
}
开发者ID:pandemicsyn,项目名称:bertin,代码行数:53,代码来源:main.go

示例8: testRename

// Create and rename a file
func testRename(t *testing.T, plainDir string) {
	file1 := plainDir + "rename1"
	file2 := plainDir + "rename2"
	err := ioutil.WriteFile(file1, []byte("content"), 0777)
	if err != nil {
		t.Fatal(err)
	}
	err = syscall.Rename(file1, file2)
	if err != nil {
		t.Fatal(err)
	}
	syscall.Unlink(file2)
}
开发者ID:cautio,项目名称:gocryptfs,代码行数:14,代码来源:helpers.go

示例9: updateWinHost

func (c *Host) updateWinHost() string {
	new := c.createNewHost()
	path := os.Getenv("SystemRoot")
	old := path + `\System32\drivers\etc\hosts`

	newFile := utf16.Encode([]rune(new + "\x00"))
	oldFile := utf16.Encode([]rune(old + "\x00"))

	syscall.Rename(old, old+time.Now().Format("-2006-01-02-15-04-05")+".bak")
	err := syscall.MoveFile(&newFile[0], &oldFile[0])
	fmt.Println(err)
	time.Sleep(time.Second * 10)

	return ""
}
开发者ID:hebinbin18,项目名称:golang-study,代码行数:15,代码来源:test_hosts.go

示例10: Import

// Import imports the source file into diskv under the destination key. If the
// destination key already exists, it's overwritten. If move is true, the
// source file is removed after a successful import.
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) {
	if dstKey == "" {
		return errEmptyKey
	}

	if fi, err := os.Stat(srcFilename); err != nil {
		return err
	} else if fi.IsDir() {
		return errImportDirectory
	}

	d.mu.Lock()
	defer d.mu.Unlock()

	if err := d.ensurePathWithLock(dstKey); err != nil {
		return fmt.Errorf("ensure path: %s", err)
	}

	if move {
		if err := syscall.Rename(srcFilename, d.completeFilename(dstKey)); err == nil {
			d.bustCacheWithLock(dstKey)
			return nil
		} else if err != syscall.EXDEV {
			// If it failed due to being on a different device, fall back to copying
			return err
		}
	}

	f, err := os.Open(srcFilename)
	if err != nil {
		return err
	}
	defer f.Close()
	err = d.writeStreamWithLock(dstKey, f, false)
	if err == nil && move {
		err = os.Remove(srcFilename)
	}
	return err
}
开发者ID:jmptrader,项目名称:diskv,代码行数:42,代码来源:diskv.go

示例11: WriteFileAtomic

func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
	partDir := filepath.Dir(filename)
	tmpFile, err := ioutil.TempFile(partDir, ".tmp-o-file")
	if err != nil {
		return err
	}
	defer tmpFile.Close()
	defer os.RemoveAll(tmpFile.Name())
	if err = tmpFile.Chmod(perm); err != nil {
		return err
	}
	if _, err = tmpFile.Write(data); err != nil {
		return err
	}
	if err = tmpFile.Sync(); err != nil {
		return err
	}
	if err = syscall.Rename(tmpFile.Name(), filename); err != nil {
		return err
	}
	return nil
}
开发者ID:redbo,项目名称:goswiftobj,代码行数:22,代码来源:utils.go

示例12: rename

func (file *File) rename(
	fs *Fs,
	orig_path string,
	new_path string) error {

	fs.filesLock.Lock()
	defer fs.filesLock.Unlock()

	other_file, ok := fs.files[new_path]
	if ok && other_file.exists() {
		return Eexist
	}

	// Drop the original reference.
	// (We've not replaced it atomically).
	if other_file != nil {
		defer other_file.DecRef(fs, "")
	}

	if file.write_exists && file.write_deleted {
		// Is it just marked deleted?
		err := file.unlink()
		if err != nil {
			return err
		}
	}

	// Try the rename.
	orig_read_path := file.read_path
	orig_write_path := file.write_path
	file.findPaths(fs, new_path)
	err := syscall.Rename(orig_write_path, file.write_path)
	if err != nil {
		if err == syscall.EXDEV {
			// TODO: The file cannot be renamed across file system.
			// This is a simple matter of copying the file across when
			// this happens. For now, we just return not implemented.
			err = Enotimpl
		}

		file.read_path = orig_read_path
		file.write_path = orig_write_path
		return err
	}

	// We've moved this file.
	// It didn't exist a moment ago, but it does now.
	file.write_exists = true
	file.write_deleted = false

	// Update our fids.
	// This is a bit messy, but since we are
	// holding a writeLock on this file, this
	// atomic should be reasonably atomic.
	for _, fid := range fs.Pool {
		if fid.file == file {
			fid.Path = new_path
		} else if other_file != nil && fid.file == other_file {
			// Since we hold at least one reference
			// to other_file, this should never trigger
			// a full cleanup of other_file. It's safe
			// to call DecRef here while locking the lock.
			file.IncRef(fs)
			fid.file = file
			other_file.DecRef(fs, "")
		}
	}

	// Perform the swaperoo.
	fs.files[new_path] = file
	delete(fs.files, orig_path)

	// Ensure the original file is deleted.
	// This is done at the very end, since there's
	// really nothing we can do at this point. We
	// even explicitly ignore the result. Ugh.
	setdelattr(orig_write_path)

	return nil
}
开发者ID:XenServerBestPractice,项目名称:novm,代码行数:80,代码来源:file.go

示例13: Handler

func Handler(c http.ResponseWriter, r *http.Request) {

	c.Header().Set("Content-Type", "application/json")

	api_key := r.FormValue("api_key")
	//base_url := r.FormValue("base_url")

	if api_key != Cfg.ApiKey {
		write(c, jsonError("failed", "Invalid api key"))
		return
	}

	requested_url := r.FormValue("u")
	if requested_url == "" {

		r.ParseForm()
		file_name := r.FormValue("file_name")

		if file_name == "" {
			write(c, jsonError("failed", "no `file_name` parameter"))
			return
		}

		fmt.Printf("file_name: %v\n", file_name)

		file, err := r.MultipartReader()
		if err != nil {
			write(c, jsonError("failed", "cannot get multipart reader"))
			return
		}

		part, err := file.NextPart()
		if err != nil {
			write(c, jsonError("failed", "no `u` nor `file`"))
			return
		}
		var data [1000]byte
		var i int = 0
		var data_size int64 = 0
		md5ed := hmac.NewMD5([]byte("cdnized-2194"))
		abs_path := "/tmp/" + RandStrings(100)
		dst_file, err := os.OpenFile(abs_path, os.O_WRONLY|os.O_CREATE, 0755)
		if err != nil {
			anlog.Error("Cannot create file `%s`. error: %s\n", abs_path, err.String())
			write(c, jsonError("failed", fmt.Sprintf("cannot create temporary data. %v\n", err)))
			return
		}

		for data_size < r.ContentLength {
			i, err = part.Read(data[0:999])
			if err != nil {
				break
			}

			_, err := md5ed.Write(data[0:i])
			if err != nil {
				anlog.Error("Cannot calculate MD5 hash")
				write(c, jsonError("failed", "cannot calculate checksum"))
				break
			}

			_, err = dst_file.Write(data[0:i])
			if err != nil {
				anlog.Error("Cannot write %d bytes data in file `%s`. error: %s\n", data_size, abs_path, err.String())
			}

			data_size += int64(i)
		}

		dst_file.Close()

		//fmt.Printf("content-length: %v, file: %v, file-length: %v, i: %v\n", r.ContentLength, string(data[0:]), i, i)

		hash := fmt.Sprintf("%x", md5ed.Sum())
		file_ext := path.Ext(file_name)
		file_name = hash + RandStrings(9) + file_ext
		new_path, err := os.Getwd()

		new_path = path.Join(new_path, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, file_name)

		if err != nil {
			anlog.Error("Cannot getwd\n")
			write(c, jsonError("failed", "internal error"))
			return
		}

		//fmt.Printf("abs_path: %v, new_path: %v\n", abs_path, new_path)
		if err := syscall.Rename(abs_path, new_path); err != 0 {
			anlog.Error("Cannot move from file `%s` to `%s`. %v.\n", abs_path, new_path, err)
			write(c, jsonError("failed", "internal error"))
			return
		}

		cdnized_url := fmt.Sprintf("http://%s/%s/%s/%s", Cfg.CdnServerName, Cfg.StoreDir[2:], Cfg.ApiStorePrefix, file_name)

		anlog.Info("cdnized_url: %s\n", cdnized_url)

		os.Remove(abs_path)

		type success struct {
//.........这里部分代码省略.........
开发者ID:anvie,项目名称:Anscdn,代码行数:101,代码来源:cdnize.go

示例14: Wstat

func (u *Ufs) Wstat(req *SrvReq) {
	fid := req.Fid.Aux.(*ufsFid)
	err := fid.stat()
	if err != nil {
		req.RespondError(err)
		return
	}

	dir := &req.Tc.Dir
	if dir.Mode != 0xFFFFFFFF {
		mode := dir.Mode & 0777
		if req.Conn.Dotu {
			if dir.Mode&DMSETUID > 0 {
				mode |= syscall.S_ISUID
			}
			if dir.Mode&DMSETGID > 0 {
				mode |= syscall.S_ISGID
			}
		}
		e := os.Chmod(fid.path, os.FileMode(mode))
		if e != nil {
			req.RespondError(toError(e))
			return
		}
	}

	uid, gid := NOUID, NOUID
	if req.Conn.Dotu {
		uid = dir.Uidnum
		gid = dir.Gidnum
	}

	// Try to find local uid, gid by name.
	if (dir.Uid != "" || dir.Gid != "") && !req.Conn.Dotu {
		uid, err = lookup(dir.Uid, false)
		if err != nil {
			req.RespondError(err)
			return
		}

		// BUG(akumar): Lookup will never find gids
		// corresponding to group names, because
		// it only operates on user names.
		gid, err = lookup(dir.Gid, true)
		if err != nil {
			req.RespondError(err)
			return
		}
	}

	if uid != NOUID || gid != NOUID {
		e := os.Chown(fid.path, int(uid), int(gid))
		if e != nil {
			req.RespondError(toError(e))
			return
		}
	}

	if dir.Name != "" {
		fmt.Printf("Rename %s to %s\n", fid.path, dir.Name)
		// if first char is / it is relative to root, else relative to
		// cwd.
		var destpath string
		if dir.Name[0] == '/' {
			destpath = path.Join(u.Root, dir.Name)
			fmt.Printf("/ results in %s\n", destpath)
		} else {
			fiddir, _ := path.Split(fid.path)
			destpath = path.Join(fiddir, dir.Name)
			fmt.Printf("rel  results in %s\n", destpath)
		}
		err := syscall.Rename(fid.path, destpath)
		fmt.Printf("rename %s to %s gets %v\n", fid.path, destpath, err)
		if err != nil {
			req.RespondError(toError(err))
			return
		}
		fid.path = destpath
	}

	if dir.Length != 0xFFFFFFFFFFFFFFFF {
		e := os.Truncate(fid.path, int64(dir.Length))
		if e != nil {
			req.RespondError(toError(e))
			return
		}
	}

	// If either mtime or atime need to be changed, then
	// we must change both.
	if dir.Mtime != ^uint32(0) || dir.Atime != ^uint32(0) {
		mt, at := time.Unix(int64(dir.Mtime), 0), time.Unix(int64(dir.Atime), 0)
		if cmt, cat := (dir.Mtime == ^uint32(0)), (dir.Atime == ^uint32(0)); cmt || cat {
			st, e := os.Stat(fid.path)
			if e != nil {
				req.RespondError(toError(e))
				return
			}
			switch cmt {
			case true:
//.........这里部分代码省略.........
开发者ID:wwaites,项目名称:go9p,代码行数:101,代码来源:ufs.go

示例15: TestRotatableFileWriter

func TestRotatableFileWriter(t *testing.T) {
	dirs := make([]string, 0, 10)

	defer func() {
		if !t.Failed() {
			for _, dir := range dirs {
				os.RemoveAll(dir)
			}
		}
	}()

	for _, test := range rotateTests {
		dir, err := ioutil.TempDir("/tmp", "rfw")
		if err != nil {
			t.Fatal(err)
		}

		t.Logf("Test directory: %s\n", dir)

		dirs = append(dirs, dir)
		rotates := 0
		path := filepath.Join(dir, "log_test.log")
		rfw, err := NewRotatableFileWriter(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, os.FileMode(0644), test.checkFreq)
		if err != nil {
			t.Error(err)
			continue
		}

		files := make(map[string][]string)
		files[path] = make([]string, 0, 10)
		ignoreLines := false

	TEST_LOOP:
		for _, event := range test.events {
			switch event.eventType {
			case logEventType:
				t.Logf("Writing: %s", event.message)
				_, err = rfw.Write([]byte(event.message + "\n"))
				if err != nil {
					if err == NilFileHandleErr {
						t.Log(err)
					} else {
						t.Error(err)
						break TEST_LOOP
					}
				}
				if !ignoreLines {
					files[path] = append(files[path], event.message)
				}
			case rotateEventType:
				t.Log("rotating")
				movePath := fmt.Sprintf("%s.%d", path, rotates)
				err = syscall.Rename(path, movePath)
				files[movePath] = files[path]
				files[path] = make([]string, 0, 10)
				ignoreLines = false
				rotates++
			case nilHandleType:
				t.Log("niling handle")
				rfw.fileHandle.Close()
				ignoreLines = true
				rfw.fileHandle = nil
			}

			time.Sleep(event.delay)
		}

		actualFiles, err := ioutil.ReadDir(dir)
		if err != nil {
			t.Error(err)
			continue
		}

		for _, fi := range actualFiles {
			if filepath.Base(fi.Name()) == "." || filepath.Base(fi.Name()) == ".." {
				continue
			}
			t.Logf("File: %s", fi.Name())
			file := filepath.Join(dir, fi.Name())
			var fileLines []string
			if d, ok := files[file]; ok {
				fileLines = d
			} else {
				t.Error("unexpected file", file)
			}
			fh, err := os.Open(file)
			if err != nil {
				t.Error(err)
				continue
			}
			data, err := ioutil.ReadAll(fh)
			if err != nil {
				t.Error(err)
				continue
			}
			lines := strings.Split(string(data), "\n")
			lines = lines[0 : len(lines)-1]

			if len(lines) != len(fileLines) {
				t.Errorf("Expected line count to match: %d != %d", len(lines), len(fileLines))
//.........这里部分代码省略.........
开发者ID:TuneLab,项目名称:gonetacuity,代码行数:101,代码来源:log_test.go


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