在Rust中检查路径和读取文件的问题



我有一个问题,试图检查一个文件是否存在,并读取它,如果它存在。

我代码:

use std::{env, fs};
use std::fs::{File, read};
use std::path::Path;
use std::process::exit;
let arg = env::args().next().expect("Please open a file via the command line!");
let path = Path::new(
&arg
);
if !path.exists() {
error!("The specified path does not exist!");
exit(101);
}
let file = read(path).expect("Could not read file!");
let content = String::from_utf8(file).expect("The file does not contain valid characters!");

像这样运行程序./program.exe a_vali_file_path.txt

期望:如果使用有效的文件路径作为第一个参数运行程序,程序将检查它是否存在。如果是,则程序读取文件内容并返回。

实际情况:程序甚至不会真正检查文件(即使路径无效,它也不会panic),如果它试图读取,它会在控制台中打印一堆字节,然后显示错误error: Utf8Error { valid_up_to: 2, error_len: Some(1) } }。如果文件存在或不存在,则会发生此行为。

env::args.next()引用了不包含UTF-8字节的可执行文件。如果你想指向下一个参数,你必须使用另一个.next()调用,或者更好的是使用Vector来存储你的参数。

使用vector存储参数的示例->

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

按你的方式解决:

fn main() {
let args = env::args()
args.next() //Points to executable (argv[0])
args.next() //Points to file (argv[1])
}

正如您所看到的,第二个解决方案不是很优雅,但是,嘿,各有各的。

最新更新