Reading file: path of file to be read

I'm trying to read file as per this example

The code is:

use std::env;
use std::fs;
use std::io::prelude::*;

fn main() {
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let filename = &args[2];

    println!("Searching for {}", query);
    // --snip--
    println!("In file {}", filename);

    let contents = fs::read_to_string(filename)
        .expect("Something went wrong reading the file");

    println!("With text:\n{}", contents);
}

The file to be read is:

I’m nobody! Who are you?
Are you nobody, too?
Then there’s a pair of us — don’t tell!
They’d banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!

As per the example, the text file should be saved at: the root level of your project

While executing I got the below error:

thread 'main' panicked at 'Something went wrong reading the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }'

The project structure is as below:

root

Did I misunderstood the meaning of root level?

The file seems in the right place. Maybe check with strace.

Did not get what you mean?

I can't reproduce your problem. I have poem.txt in the project's root (in the same place as Cargo.toml) and it works.

running with strace will show you the syscalls like:

(openat(AT_FDCWD, "poem.txt", O_RDONLY|O_CLOEXEC) = 3)

strace cargo run the poem.txt

maybe that way you can be sure it's trying to read the right file.

strace: command not found

Oh sorry. I assumed you had strace and was on Linux.

I have no idea what the problem could be. I tried with a directory with a space in its name and it still worked.

I'm assuming you have some code in "// --snip--". I would test without that code. Maybe in another directory.

Or you could try with an absolute path. Or make sure that poem.txt exists by running ls or dir in the same place you run cargo run.

I'm on Mac, the file is in the root by running ls

There is nothing in the // --snip--

In order to make sure the poem.txt file name doesn't contain any weird character please change above line like follows:

println!("In file <{}>", filename);

The filename is correct :frowning:

Then please do:
pwd

ls -l poem.txt
in a terminal.

It gave: ls: poem.txt: No such file or directory

It seem the file is not there, or it has weird characters in its filename that are not appearing in file listings. Try renaming the existing file, or removing it and creating a new one.

1 Like

Did you run println!("In file <{}>", filename); before you told me that the filename is correct?

If yes then the file is somewhere else.

Thanks, it worked by created new file, but still do not understand what happened!

Please also run the pwd command to make sure you are in the correct directory.

File is in the wrong directory, it should be located in the appropriate target subdirectory along with the built binaries.