Skip to content

Commit

Permalink
Add mkdtemp
Browse files Browse the repository at this point in the history
  • Loading branch information
DBLouis committed Sep 21, 2020
1 parent bf77f50 commit 6ad722a
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,40 @@ pub fn mkstemp<P: ?Sized + NixPath>(template: &P) -> Result<(RawFd, PathBuf)> {
Ok((fd, PathBuf::from(pathname)))
}

/// Creates a directory which persists even after process termination
///
/// * `template`: a path whose 6 rightmost characters must be X, e.g. `/tmp/tmpdir_XXXXXX`
/// * returns: filename
///
/// Err is returned either if no temporary filename could be created or the template doesn't
/// end with XXXXXX
///
/// See also [mkstemp(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html)
///
/// ```rust
/// use nix::unistd;
///
/// match unistd::mkdtemp("/tmp/tempdir_XXXXXX") {
/// Ok(_path) => {
/// // do something with directory
/// }
/// Err(e) => panic!("mkdtemp failed: {}", e)
/// };
/// ```
#[inline]
pub fn mkdtemp<P: ?Sized + NixPath>(template: &P) -> Result<PathBuf> {
let mut path = template.with_nix_path(|path| {path.to_bytes_with_nul().to_owned()})?;
let p = path.as_mut_ptr() as *mut _;
let p = unsafe { libc::mkdtemp(p) };
if p.is_null() {
return Err(Error::Sys(Errno::last()));
}
let last = path.pop(); // drop the trailing nul
debug_assert!(last == Some(b'\0'));
let pathname = OsString::from_vec(path);
Ok(PathBuf::from(pathname))
}

/// Variable names for `pathconf`
///
/// Nix uses the same naming convention for these variables as the
Expand Down

0 comments on commit 6ad722a

Please sign in to comment.