How to create a file according to a given file name

Hello !

I’m working on how to create a file according to a give file name :

	use std::io;
use std::io::Write;
use std::io::prelude::*;
use std::fs::File;

fn main()
	print!("Name of the file : ");
		.expect("Error : Failed to flush buffer");
	//Getting user input
	let mut user_input = String::new();
	io::stdin().read_line(&mut user_input)
		.expect("Error : Failed to read user input");
	//Creating the file
	let mut file = File::create(user_input)
		.expect("Error : Failed to create the file");
	println!("Writing in file {}", user_input);
	//Ereasing the content of user_input
	user_input = String::from("");
	//Getting user input
	io::stdin().read_line(&mut user_input)
		.expect("Error : Failed to get user input");
	//Writing to the file
	//Converting input to bytes
		.expect("Error : Failed to write to the file");

Indeed, I would like to create a file according to what the user would like it to be named. But it doesn’t work that way, what is the right way ?


Ok I just found the solution !

Lesson of the day : When you use a mutable variable, dont forget to add &mut in your expression.

let foo = File::create(&mut user_input);

You could also write

let foo = File::create(&user_input);

because File::create doesn’t use a mutable parameter.

Minor nit-pick: using String is unnecessary here, because paths aren’t necessarily UTF-8 encoded. You should probably just let the user type in whatever bytes they want until a newline.

Edit: Nevermind, it’s more hellish than I thought it was.

1 Like