Skip to main content

rename

Function rename 

1.0.0 · Source
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> Result<()>
Expand description

Renames a file or directory to a new name, replacing the original file if to already exists.

This will not work if the new name is on a different mount point.

§Platform-specific behavior

This function currently corresponds to the rename function on Unix, and MoveFileExW with a fallback to SetFileInformationByHandle on Windows. The exact behavior differs:

  • If to does not exist, from can be anything.
  • On Unix, when from is a directory and to exists, to must be an empty directory.
  • On Unix, when from is not a directory and to exists, to may not be a directory.
  • On Windows 10 version 1607 and above, the behavior is the same as Unix if the filesystem supports FileRenameInfoEx.
  • Otherwise on Windows, from can be anything but to must not be a directory.

Note that, this may change in the future.

§Errors

This function will return an error in the following situations, but is not limited to just these cases:

  • from does not exist.
  • The user lacks permissions to view contents.
  • from and to are on separate filesystems.

§Examples

use std::fs;

fn main() -> std::io::Result<()> {
    fs::rename("a.txt", "b.txt")?; // Rename a.txt to b.txt
    Ok(())
}