I would like to have a rust program compiled, and afterwards have that compiled binary file's contents saved in another rust program as a variable, so that it can write that to a file. So for example, if I have an executable file which prints hello world, I would like to copy it as a variable to my second rust program, and for it to write that to a file. Basically an executable which creates an executable. I dont know if such thing is possible, but if it is I would like to know how it's done.
Asked
Active
Viewed 357 times
0
-
Does this answer your question? [What's the de-facto way of reading and writing files in Rust 1.x?](https://stackoverflow.com/questions/31192956/whats-the-de-facto-way-of-reading-and-writing-files-in-rust-1-x) Specifically the "Read a file as a `Vec
`" part of the top-rated answer. – hnefatl Feb 28 '22 at 22:55 -
I want to also include an executable as a variable – michael morrison Feb 28 '22 at 23:02
-
Is reading an executable file any different from reading any other file? – hnefatl Feb 28 '22 at 23:08
1 Answers
3
Rust provides macros for loading files as static variables at compile time. You might have to make sure they get compiled in the correct order, but it should work for your use case.
// The compiler will read the file put its contents in the text section of the
// resulting binary (assuming it doesn't get optimized out)
let file_contents: &'static [u8; _] = include_bytes!("../../target/release/foo.exe");
// There is also a version that loads the file as a string, but you likely don't want this version
let string_file_contents: &'static str = include_str!("data.txt");
So you can put this together to create a function for it.
use std::io::{self, Write};
use std::fs::File;
use std::path::Path;
/// Save the foo executable to a given file path.
pub fn save_foo<P: AsRef<Path>>(path: P) -> io::Result<()> {
let mut file = File::create(path.as_ref().join("foo.exe"))?;
file.write_all(include_bytes!("foo.exe"))
}
References:

Locke
- 7,626
- 2
- 21
- 41