How to create a file in a specific directory?

Let's say I have a directory: /home/sayan/data/ and I want to create a file in that folder, while my application is running somewhere else, how can I achieve that?
I tried using std::path::PathBuf to build the path, but now I'm kinda lost.
It'd be great if someone provides some guidance (while I read the docs!)

You can use PathBuf or Path (the difference is like between String and &str, i.e. one is owned and permanent and can be freely passed around, and the other is a temporary view limited to a scope).

You can append to a path:

let file_path = PathBuf::from("/home/sayan/data/").join(file_name);

and make files with:

std::fs::write(&file_path, "Hello");
3 Likes

I found a different way to do that, but yeah thanks for that too!

Mind to share your method?

let mut path = PathBuf::new();
path.push("/home/sayan/data/boot.cfg");
// buffer_stream is a method that gets the contents
// it'll obviously be different in your case!
let contents = server::buffer_stream(&key).load_document().unwrap(); 
let mut file = File::create(path)?;
file.write_all(contents.as_bytes())?;
// io::Result handled by some logic

That's all! :slight_smile:

Regards,
Sayan

1 Like
File::create("/home/sayan/data/boot.cfg");

works too, because it takes AsRef<Path>, and strings and a few other types are path-compatible.

1 Like

Oh thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.