“#包括"C 程序中的文本文件作为 char[]

人气:589 发布:2022-10-16 标签: include c c-preprocessor

问题描述

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

something like:

file.txt:

This is
a little
text file

main.c:

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

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

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?

解决方案

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

$ echo hello world > a
$ xxd -i a

outputs:

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

783