Skip to content

Commit

Permalink
Add mkdtemp
Browse files Browse the repository at this point in the history
  • Loading branch information
DBLouis committed Aug 10, 2021
1 parent 68488a4 commit 8a3a875
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased] - ReleaseDate
### Added

- Added `mkdtemp` wrapper
(#[1297](https://github.com/nix-rust/nix/pull/1297))
- Added `TimeSpec::from_duration` and `TimeSpec::from_timespec`
(#[1465](https://github.com/nix-rust/nix/pull/1465))
- Added `IPV6_V6ONLY` sockopt.
Expand Down
32 changes: 32 additions & 0 deletions src/unistd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1788,6 +1788,38 @@ 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 rightmost characters contain some number of X, e.g. `/tmp/tmpdir_XXXXXX`
/// * returns: filename
///
/// Err is returned either if no temporary filename could be created or the template had insufficient X
///
/// See also [mkstemp(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html)
///
/// ```
/// use nix::unistd;
///
/// match unistd::mkdtemp("/tmp/tempdir_XXXXXX") {
/// Ok(_path) => {
/// // do something with directory
/// }
/// Err(e) => panic!("mkdtemp failed: {}", e)
/// };
/// ```
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 8a3a875

Please sign in to comment.