How to get the absolute path of the file from `File`, but the related API is not found?

[dependencies]
tempfile = "3.2.0"
use std::fs::File;
use std::io::{Write, Read, Seek, SeekFrom};
use std::path::Path;

fn main() {
    // Write
    let mut tmpfile: File = tempfile::tempfile().unwrap();
    write!(tmpfile, "Hello World!").unwrap();

    println!("{}", tempfile.abspath); // ??? How to get the absolute path?
}

A File does not know its own path. This is because it is a thin wrapper around a file descriptor, and there isn't necessarily a canonical path for every file descriptor. In particular, tempfile() removes the file from the filesystem after opening it, so it does not exist at any path.

You can use tempfile::NamedTempFile if you want a temporary file with a valid path:

use tempfile::NamedTempFile;

fn main() {
    let tmpfile = NamedTempFile::new().unwrap();
    write!(tmpfile, "Hello World!").unwrap();
    println!("{:?}", tmpfile.path());
}
2 Likes

How to monitor the program under mac, is the written file really deleted? Are there any tools to monitor?

I found the relevant information, but did not find any available.

The std::fs::File returned from tempfile::tempfile() points to a file which has been "unlinked" from the filesystem, making it inaccessible to all external processes. That means other programs won't be able to monitor it. When the File is dropped or the process exits, the OS will automatically garbage collect the data because it is no longer used by the filesystem or any process.

You should probably be more specific when you say "monitor", too. I'm guessing you just want to see the file's contents (kinda like tail -f path/to/file.txt), in which case you should create a NamedTempFile as mentioned earlier.

The requirements I want to do are:
Release two files, execute the program and dylib file;
I need to get the path and execute it.

I have solved it by NamedTempFile now, thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.