0

I have some text files in my project's folder on the same level as my src folder. I have a run function that gets user input and makes a readfile struct from it.

    pub fn run() {
        loop {
            let file = ReadFile::println_recieve_h("What is the filepath?");
            let query = ReadFile::println_recieve_h("What phrase do you want to find?");
            let readfile = ReadFile::new(&file, &query);
            ...

Here is the helper function that I made to reduce redundancy (I believe I have isolated the issue here):

    fn println_recieve_h(print: &str) -> String {
        println!("{print}");
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        input
    }

Here is the function that invokes the point of failure

pub struct ReadFile{ query: String, file_path: String, contents: String }

impl ReadFile {
    //Builds a readfile struct with a path and phrase.
    fn new(file_path: &String, phrase: &String) -> ReadFile{
        use std::fs;
        ReadFile {  
            query: phrase.clone(), 
            file_path: file_path.clone(), 
            contents: fs::read_to_string(file_path).expect("ERROR 003: FILE NOT FOUND"), 
        }
    }

contents: fs::read_to_string(file_path).expect("ERROR 003: FILE NOT FOUND") fails with the use case however succeeds with hardcoded string slice (I have tried converting the string reference to a slice). Example: contents: fs::read_to_string("longtxt1.txt").expect("ERROR 003: FILE NOT FOUND").

Does anyone see the problem that is causing this? I am new to Rust.

I have tried converting the reference to a string slice, cloning the reference, etc. I made sure there are no spelling errors when I do my inputs in the console. I have hardcoded file in the run function to String::from("longtxt1.txt") which makes everything work. I believe this isolates the issue to my usage of the helper function.

Wisp
  • 3
  • 1
  • RESOLVED: I found out read_line contains invisible characters at the end by checking the string length. This follows what Colonel Thirty Two responded. I'll keep this up so others don't make the same newbie mistake. – Wisp Dec 04 '22 at 19:17

1 Answers1

0

read_line includes a trailing newline in the returned string, which is not in your filename. You'll need to trim the returned string.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85