Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed data in a C++ program

Tags:

c++

linux

sqlite

I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource.

(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)

Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)

like image 381
Head Geek Avatar asked Sep 16 '08 14:09

Head Geek


People also ask

How do you execute file input and output in C programming?

File Input and Output in C 1) Create a variable to represent the file. 2) Open the file and store this "file" with the file variable. 3) Use the fprintf or fscanf functions to write/read from the file.

How do you create a file in C?

To create a file in a 'C' program following syntax is used, FILE *fp; fp = fopen ("file_name", "mode"); In the above syntax, the file is a data structure which is defined in the standard library. fopen is a standard function which is used to open a file.

What is Bin2C?

Bin2C is a command-line utility for Windows which takes a binary (or HTML or text) file as input and converts it to a C-array that can be directly included in target application code.


2 Answers

You can use objcopy to bind the contents of the file to a symbol your program can use. See, for instance, here for more information.

like image 160
moonshadow Avatar answered Sep 20 '22 11:09

moonshadow


Use macros. Technically that file would be source code file but it wouldn't look like this. Example:

//queries.incl - SQL queries
Q(SELECT * FROM Users)
Q(INSERT [a] INTO Accounts)


//source.cpp
#define Q(query) #query,
char * queries[] = {
#include "queries.incl"
};
#undef Q

Later on you could do all sorts of other processing on that file by the same file, say you'd want to have array and a hash map of them, you could redefine Q to do another job and be done with it.

like image 36
vava Avatar answered Sep 20 '22 11:09

vava