如何在编译时生成文本文件并将其内容包含在输出中? [英] How do I generate a text file during compile time and include its content in the output?

查看:155
本文介绍了如何在编译时生成文本文件并将其内容包含在输出中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试与如何做在编译时创建静态字符串

use std::{env};
use std::path::Path;
use std::io::{Write, BufWriter};
use std::fs::File;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("file_path.txt");
    let mut f = BufWriter::new(File::create(&dest_path).unwrap());

    let long_string = dest_path.display();
    write!(f, "{}", long_string).unwrap();
}



main.rs



main.rs

fn main() {

    static LONG_STRING: &'static str = include_str!("file_path.txt");
    println!("{}", LONG_STRING);
}

货物建造我收到错误消息:

error: couldn't read src\file_path.txt: The system cannot find the file specified. (os error 2)
 --> src\main.rs:3:40
  |
3 |     static LONG_STRING: &'static str = include_str!("file_path.txt");
  |                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我可以看到文件是在

X:\source\github\rust-build-script-example\target\debug\build\rust-build-script-example-f2a03ef7abfd6b23\out\file_path.txt




  1. 为了获得<$ c $,我必须使用什么环境变量而不是OUT_DIR? c> file_path.txt 是否要输出到 src 目录?

  2. 如果无法执行#1 ,那么我如何在上述目录中 include_str!生成的文件而不用代码对其进行硬编码(因为该路径似乎具有随机生成的部分 rust -build-script-example-f2a03ef7abfd6b23

  1. What is the environment variable I have to use instead of OUT_DIR in order to get the file_path.txt to be output to the src directory?
  2. If #1 is not possible, then how do I include_str! the generated file in the above directory without hardcoding it in code (since the path seems to have a randomly generated partial rust-build-script-example-f2a03ef7abfd6b23 in it)

我的GitHub存储库

推荐答案

诀窍是

concat!(env!("OUT_DIR"), "/file_path.txt")

我按如下所示更改了main.rs并成功了。

I changed my main.rs as follows and it worked.

fn main() {

    static LONG_STRING: &'static str = include_str!(concat!(env!("OUT_DIR"), "/file_path.txt"));

    println!("{}", LONG_STRING);
}

以下crates.io文档提供了帮助

The following crates.io documentation helped

http://doc.crates.io/build-script.html

https://doc.rust-lang.org/cargo/reference/environment-variables.html

这篇关于如何在编译时生成文本文件并将其内容包含在输出中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆