Thread: Best way to embed data in source code?

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    12

    Best way to embed data in source code?

    I have a program that reads about 10K of data. This data will never change. It's all constants, etc.

    So it seems I have these options:

    • I could just include a ".dat" or ".txt" file with the program, in either binary or text format and have the program read and parse as part of its startup.
    • I could unroll it all in the source code and have a subroutine that is simply thousands of "somevar[14] = 1.2;", etc. assignment lines. (Obviously, I could collapse arrays down to a single assignment, but you get my idea).
    • Or...is there a way to embed the data in the source some other way? I'm thinking of a mechanism like perl's __DATA__.


    I suspect it's either external .dat/.txt or lots of assignment lines, but I thought I'd ask if there are other techniques people use...?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well it depends what format the data is in (how many data types).

    If they're all ints say, and separated by commas, then this works rather neatly.
    Code:
    int mydata[] = {
    #include "data.h"
    };
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    I would make a small throw-away program that reads the data and spits out a comma delimited list. Perhaps using the most physically compact form of constants such as hex and choose large integers like 32 bit or 64 bit. This "source" code will then be hard-coded in your program as a global assignment.

  4. #4
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    If you're using Windows, you could embed the files as resources.

    Otherwise, do what is suggested above.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help in C programming (too lazy)
    By cwillygs in forum C Programming
    Replies: 12
    Last Post: 04-20-2010, 12:23 AM
  2. Compiling C in Visual Studio 2005
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-16-2009, 04:25 AM
  3. Code review
    By bennywhere in forum C Programming
    Replies: 16
    Last Post: 10-20-2009, 09:00 PM
  4. Reading a file with Courier New characters
    By Noam in forum C Programming
    Replies: 3
    Last Post: 07-07-2006, 09:29 AM
  5. Code and data size
    By Roaring_Tiger in forum C Programming
    Replies: 1
    Last Post: 03-24-2003, 10:16 PM