michael morrison
michael morrison

Reputation: 9

Saving a binary as a rust variable

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.

Upvotes: 0

Views: 632

Answers (1)

Locke
Locke

Reputation: 8944

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:

Upvotes: 3

Related Questions