0

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.

3
  • Does this answer your question? What's the de-facto way of reading and writing files in Rust 1.x? Specifically the "Read a file as a Vec<u8>" part of the top-rated answer. Commented Feb 28, 2022 at 22:55
  • I want to also include an executable as a variable Commented Feb 28, 2022 at 23:02
  • Is reading an executable file any different from reading any other file? Commented Feb 28, 2022 at 23:08

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

You used include_bytes in your string example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.