1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

truncate: create non-existent file by default

Fix the behavior of truncate when given a non-existent file so that it
correctly creates the file before truncating it (unless the
`--no-create` option is also given).
This commit is contained in:
Jeffrey Finkelstein 2022-01-23 11:14:48 -05:00
parent 8a787fe028
commit 129cfe12b8
2 changed files with 35 additions and 3 deletions

View file

@ -278,9 +278,16 @@ fn truncate_size_only(
Err(e) => crash!(1, "Invalid number: {}", e.to_string()),
};
for filename in &filenames {
let fsize = usize::try_from(metadata(filename)?.len()).unwrap();
let tsize = mode.to_size(fsize);
file_truncate(filename, create, tsize)?;
let fsize = match metadata(filename) {
Ok(m) => m.len(),
Err(_) => 0,
};
let tsize = mode.to_size(fsize as usize);
match file_truncate(filename, create, tsize) {
Ok(_) => continue,
Err(e) if e.kind() == ErrorKind::NotFound && !create => continue,
Err(e) => return Err(e),
}
}
Ok(())
}

View file

@ -321,3 +321,28 @@ fn test_truncate_bytes_size() {
}
}
}
/// Test that truncating a non-existent file creates that file.
#[test]
fn test_new_file() {
let (at, mut ucmd) = at_and_ucmd!();
let filename = "new_file_that_does_not_exist_yet";
ucmd.args(&["-s", "8", filename])
.succeeds()
.no_stdout()
.no_stderr();
assert!(at.file_exists(filename));
assert_eq!(at.read_bytes(filename), vec![b'\0'; 8]);
}
/// Test for not creating a non-existent file.
#[test]
fn test_new_file_no_create() {
let (at, mut ucmd) = at_and_ucmd!();
let filename = "new_file_that_does_not_exist_yet";
ucmd.args(&["-s", "8", "-c", filename])
.succeeds()
.no_stdout()
.no_stderr();
assert!(!at.file_exists(filename));
}