0

I need to store something in source as a char array so I can read it later,

how to store it in source file as char pointer and how to convert a binary file to char pointer?

I remember I saw some demo before that use this way to publish small demo without carry some small files, such as 5k or even 100k size of file.

user1051003
  • 1,211
  • 5
  • 16
  • 24
  • oh, the "size of file" edit at the end of the post really made things clear now. – Mike Nakis Dec 28 '11 at 14:08
  • If I understand correctly, you wish to embed binary data into your executable so that you don't need to supply it as a separate file? – Oliver Charlesworth Dec 28 '11 at 14:10
  • yes that's it, I am using gcc and pure c, I think I need a way to convert a binary file to some sort of format and paste in as char *file1 ={paste stuff}; ??? – user1051003 Dec 28 '11 at 14:13
  • possible duplicate of ["#include" a text file in a C program as a char\[\]](http://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char). I also think [my answer](http://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char/411000#411000) fits. – Hasturkun Dec 28 '11 at 14:44

3 Answers3

2

The xxd tool can do this:

xxd -i inputfile
caf
  • 233,326
  • 40
  • 323
  • 462
0

I usually use a simple Perl/Ruby/Python script to convert binary data to C source code:

# Python script bin_to_c.py
import sys

i = 0
res = []
res.append("unsigned char data[] = \"")
for c in sys.stdin.read():
  if i % 15 == 0:
    res.append("\"\n    \"")
  res.append("\\x%02x" % ord(c))
  i += 1

print ''.join(res) + '";'
print "size_t data_size = sizeof(data) - 1;"

You can then paste the output into a C file, like this:

python bin_to_c.py < input.bin > data.c
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
0

I'm not sure whether you want to open a binary file or binary mode.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp = NULL;
    int len = 0;
    char * file_buff = NULL;

    if ((fp = fopen("file1", "rb")) == NULL) {
        printf("Failed to open file\n"); 
        return EXIT_FAILURE;
    }   

    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    if ((file_buff = (char *) malloc((int)sizeof(char) * len)) == NULL) {
        printf("ERROR: unable to allocate memory\n");
        return EXIT_FAILURE;
    }   

    fread(file_buff, len, 1, fp);   
    fclose(fp);

    printf("Contents of the file : \n%s", file_buff);

    /* do whatever you wanted to do with file_buff here */

    /* once done, free the file buffer */
    free(file_buff);

    return EXIT_SUCCESS;
}
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98