"#包括"在C程序中的文本文件作为一个char [] [英] "#include" a text file in a C program as a char[]

查看:119
本文介绍了"#包括"在C程序中的文本文件作为一个char []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法,包括整个文本文件在编译时在C程序中的字符串?

Is there a way to include an entire text file as a string in a C program at compile-time?

是这样的:


  • file.txt的:

  • file.txt:

This is
a little
text file


  • main.c中:

  • main.c:

    #include <stdio.h>
    int main(void) {
       #blackmagicinclude("file.txt", content)
       /*
       equiv: char[] content = "This is\na little\ntext file";
       */
       printf("%s", content);
    }
    


  • 获得一个小程序,在标准输出上打印这是
    一点
    文本文件

    obtaining a little program that prints on stdout "This is a little text file"

    目前,我用了一个的hackish python脚本,但它的对接丑陋,仅限于​​一个变量名,你能告诉我另一种方式来做到这一点?

    At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?

    推荐答案

    我建议使用(UNIX UTIL) XXD 了解这一点。
    你可以用它像这样

    I'd suggest using (unix util)xxd for this. you can use it like so

    $ echo hello world > a
    $ xxd -i a
    

    输出:

    unsigned char a[] = {
      0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
    };
    unsigned int a_len = 12;
    

    这篇关于&QUOT;#包括&QUOT;在C程序中的文本文件作为一个char []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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