C/C++, can you #include a file into a string literal?

This question already has an answer here:

  • “#include” a text file in a C program as a char[] 15 answers

  • The C/C++ preprocessor acts in units of tokens, and a string literal is a single token. As such, you can't intervene in the middle of a string literal like that.

    You could preprocess script.py into something like:

    "some coden"
    "some more code that will be appendedn"
    

    and #include that, however. Or you can use xxd ​ -i to generate a C static array ready for inclusion.


    This won't get you all the way there, but it will get you pretty damn close.

    Assuming script.py contains this:

    print "The current CPU time in seconds is: ", time.clock()
    

    First, wrap it up like this:

    STRINGIFY(print "The current CPU time in seconds is: ", time.clock())
    

    Then, just before you include it, do this:

    #define STRINGIFY(x) #x
    
    const char * script_py =
    #include "script.py"
    ;
    

    There's probably an even tighter answer than that, but I'm still searching.


    The best way to do something like this is to include the file as a resource if your environment/toolset has that capability.

    If not (like embedded systems, etc.), you can use a bin2c utility (something like http://stud3.tuwien.ac.at/~e0025274/bin2c/bin2c.c). It'll take a file's binary representation and spit out a C source file that includes an array of bytes initialized to that data. You might need to do some tweaking of the tool or the output file if you want the array to be '' terminated.

    Incorporate running the bin2c utility into your makefile (or as a pre-build step of whatever you're using to drive your builds). Then just have the file compiled and linked with your application and you have your string (or whatever other image of the file) sitting in a chunk of memory represented by the array.

    If you're including a text file as string, one thing you should be aware of is that the line endings might not match what functions expect - this might be another thing you'd want to add to the bin2c utility or you'll want to make sure your code handles whatever line endings are in the file properly. Maybe modify the bin2c utility to have a '-s' switch that indicates you want a text file incorportated as a string so line endings will be normalized and a zero byte will be at the end of the array.

    链接地址: http://www.djcxy.com/p/72120.html

    上一篇: 在flex / lex中的字符串文字的正则表达式

    下一篇: C / C ++,你可以#将一个文件包含到字符串中吗?