Read a text file into a vector of strings

fn read_file() -> std::io::Result<Vec<String>> {
    let mut list: Vec<String> = Vec::new();
    let file = File::open("names.txt")
        .expect("File not found");
    let buf = BufReader::new(file);

    for line in buf.lines() {
        list.push(line?);
    }
    Ok(list)
}
``` this code returns a vector of strings but returns a vector.len() of 1 for the whole list. Also backslashes appear in the output: ...,\"ELDEN\",\"DORSEY\",\"DARELL\",\"BRODERICK\",\"ALONSO\""]. The original text quotes and commas to separate names w/o slashes and this code adds an extra set of quotes at the beginning and end from collecting the strings into a long string.
How do I fix this so that the vector contains individual strings without the slashes.

the extra quotes and slashes are not being added by this code, but by whatever code you are using to print the list. they are not actually in the strings, Debug prints strings as if they were string literals.

it's the same as how the rust string literal "\"abc\"" represents the string "abc".

Here the lines method breaks the input file into lines based upon:

  • newlines (\n), or
  • sequences of a carriage return followed by a line feed (\r\n)

If the target file contains a series of comma-separated values, and each value is a string surrounded by quotes, then it is possible there are no end of line delimiters. In this case the whole file would read in as a single line, resulting in list containing a single element.

The code snippet you provide does not show how you are producing the output quoted in your comment. Since the values separated by commas are wrapped in quotes, a Debug representation can include an escape character before the quote, so if you have test code like this...

let data = read_file(path).expect("File not found.");
println!("Result is {data:?}");

...then it will insert escapes before quotes as you have observed. Likely, you want to strip the quotes from the character strings and save the inner values instead, perhaps by using trim_matches:

let data = read_to_string(path).expect("File not found.");
let data = data.trim_matches('"');
println!("Result is {data}");

This inspired me to do something I'd been thinking about for a while and go open Add `fs::read_lines` to simplify getting a `Vec<String>` · Issue #522 · rust-lang/libs-team · GitHub to propose that we have a convenience method for this.