How to include a text file along with a crate installation

1.5k Views Asked by At

My program works as expected with my local machine. It prints random lines from a text file in the vein of the Emacs "Spook" amusement (M-x spook). The text file is located in 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>

But if I publish it as a crate and install it, the text file is not found (because it is not in src/spook.lines if the program is installed from crates.io):

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)

The way I include the file is:

let file = File::open("src/spook.lines")?;

Why can I not just tell the cargo/crate packaging to include the text file? What is the preferred way? I mean even if I include the file in a certain directory then it would not be in the PATH of the execution because the program might be run from anywhere.

1

There are 1 best solutions below

2
Jan van den Berg On

You can use the include_str! macro.

fn main() {
    let my_str = include_str!("spanish.in");
    assert_eq!(my_str, "adiós\n");
    print!("{}", my_str);
}

https://doc.rust-lang.org/std/macro.include_str.html