Description
Proposal
Problem statement
Currently, when people want to write log file, he/she must write verbose & unreadable & error-prone code, such as:
let mut file = File::options().append(true).create(true).open("./log.txt").unwrap();
let _ = file.write_fmt(format_args!("log text\n"));
The use of File::options()....
also requires people thinking more about permissions & flags in detail:
- should I need a READ permission? (
.open(true)
?) - should I need a WRITE permission? (
.write(true)
?) - maybe I forget to write
.create(true)
(error-prone) - Is there any other flags must be used? (need check more docs)
It requires people reading more docs and it's not easy to remember them all. Next time will do these again and again.
So, we need a small wrapper methods around File::options().append(true).create(true).open("./log.txt")
, to make life better.
Motivating examples or use cases
A common use case is open logging file and write new lines to it's end, the file may be exists or not:
fn log(line: &str) {
let mut file = File::append("./log.txt").unwrap(); // <-- use new File::append
let _ = file.write_fmt(format_args!("{line}\n"))
}
the File::append("./log.txt")
is very easy to use than File::options().append(true).create(true).open("./log.txt")
, and it's more readable (for review).
Solution sketch
Add to std::fs::File
:
// open existing or create new file for append data.
// very useful when writing log files.
pub fn append<P: AsRef<Path>>(path: P) -> io::Result<File> {
OpenOptions::new().append(true).create(true).open(path.as_ref())
}
Alternatives
n/a
Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.