我的程序可以在本地计算机上正常工作。它在Emacs“ Spook”娱乐(M-x spook)的静脉中打印来自文本文件的随机行。文本文件位于src/spook.lines
中。
C:\Users\datan>spooks
domestic Eiffel Tower Euzkadi Ta Askatasuna Euzkadi Ta Askatasuna minefield
C:\Users\datan>spooks
Uzi White House secret Sivi Vukovi divers
C:\Users\datan>spooks
Hizb-i-Islami smallpox US Airways SWAT plague
C:\Users\datan>
但是如果我publish it as a crate并安装它,则找不到文本文件(因为如果从crates.io安装程序,则该文本文件不在src/spook.lines
中):
C:\Users\datan>docker run -it rust bash
Unable to find image 'rust:latest' locally
latest: Pulling from library/rust
16ea0e8c8879: Pull complete
50024b0106d5: Pull complete
ff95660c6937: Pull complete
9c7d0e5c0bc2: Pull complete
29c4fb388fdf: Pull complete
ee0ab7fd0ac4: Pull complete
Digest: sha256:d8e2b124d6f4fcdf977bf7e6cfbda87fa5061b0c1933742699ee5131444217c9
Status: Downloaded newer image for rust:latest
root@137111b4d94c:/# cargo install spooks
Updating crates.io index
Downloaded spooks v0.1.0
Downloaded 1 crate (19.0 KB) in 1.60s
Installing spooks v0.1.0
Downloaded getopts v0.2.21
Downloaded rand v0.7.2
Downloaded rand_chacha v0.2.1
Downloaded easy_reader v0.5.0
Downloaded getrandom v0.1.13
Downloaded rand_core v0.5.1
Downloaded unicode-width v0.1.7
Downloaded libc v0.2.66
Downloaded c2-chacha v0.2.3
Downloaded fnv v1.0.6
Downloaded cfg-if v0.1.10
Downloaded ppv-lite86 v0.2.6
Compiling libc v0.2.66
Compiling getrandom v0.1.13
Compiling cfg-if v0.1.10
Compiling ppv-lite86 v0.2.6
Compiling fnv v1.0.6
Compiling unicode-width v0.1.7
Compiling getopts v0.2.21
Compiling c2-chacha v0.2.3
Compiling rand_core v0.5.1
Compiling rand_chacha v0.2.1
Compiling rand v0.7.2
Compiling easy_reader v0.5.0
Compiling spooks v0.1.0
Finished release [optimized] target(s) in 22.15s
Installing /usr/local/cargo/bin/spooks
Installed package `spooks v0.1.0` (executable `spooks`)
root@137111b4d94c:/# spooks
(no output because src/spook.lines is not there)
我包含文件的方式是:
let file = File::open("src/spook.lines")?;
为什么我不能仅告诉货物/板条箱包装包含文本文件?首选方式是什么?我的意思是,即使我将文件包含在某个目录中,它也不会位于执行的PATH
中,因为该程序可能从任何地方运行。
答案 0 :(得分:0)
您可以使用include_str!
宏。
fn main() {
let my_str = include_str!("spanish.in");
assert_eq!(my_str, "adiós\n");
print!("{}", my_str);
}
答案 1 :(得分:0)
感谢这里的评论,以下作品:
fn spook() -> Result<(), Error> {
// Create fake "file"
let mut c = Cursor::new(Vec::new());
let str42 = include_str!("spook.lines").as_bytes();
// Write into the "file" and seek to the beginning
c.write_all(str42).unwrap();
c.seek(SeekFrom::Start(0)).unwrap();
let mut reader = EasyReader::new(c)?;
let _res = reader.build_index();
print!("{}", reader.random_line()?.unwrap());
print!("{}", reader.random_line()?.unwrap());
print!("{}", reader.random_line()?.unwrap());
print!("{}", reader.random_line()?.unwrap());
print!("{}", reader.random_line()?.unwrap());
Ok(())
}