Question

Simple question I know, what I want to do is be able to get the bytes of a file to use to add those bytes to an bit array, which I can then use to write to a file named bytes.exe and launch it. I know how to read the bytes of an existing file at runtime. But I don't know how to get the bytes of a file to copy and paste into my bitarray[] at design time.

The goal is to be able to write the bites of bitarray[] to myfile.exe at runtime, and then launch said file. There are many bitarray[]'s I'll be using, based on many different file types, so I'm looking for an easy method.

Is there some kind of decompiler that should be used? I just looked into resource scripts, but I don't want to attach any dependencies to my main .exe.

Was it helpful?

Solution

If you are targeting Windows, the easiest way to do this is to embed myfile.exe as a resource, then load the resource at runtime and create a file and write the contents of the resource to your new file.

If you can't use resources, then you'll need to create a source file (.c or .h) that initializes a byte array with the contents of myfile.exe and include that as part of your build. Check out this answer for one possible approach:

https://stackoverflow.com/a/73653/333127

EDIT: After further review, I don't think the source code in the link I referenced above will work for binary input files. Here's a quick alternative I just threw together:

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

#define BYTES_PER_LINE 70

int main(int argc, char* argv[])
{
    FILE* fp;
    int ch;
    int numBytes = 0;

    if (argc < 2) {
        printf("Usage: tobytes <file>\n");
        exit(1);
    }

    fp = fopen(argv[1], "rb");
    if (fp == NULL) {
        printf("Cannot open file %s\n", argv[1]);
        exit(1);
    }

    printf("char fileContents[] = {\n");
    while ((ch = fgetc(fp)) != EOF) {
        if (numBytes > 0)
            printf(",");

        ++numBytes;
        if (numBytes % BYTES_PER_LINE == 0)
            printf("\n");

        printf("0x%x", ch);
    }
    printf("\n};\n");

    fclose(fp);

    return 0;
}

OTHER TIPS

It's not 100% clear what you want to do, but why not write a small program that reads a file and translates it into a C array.

That is if the file data is:

01 02 03 04 (binary)

The program will generate a file that is:

char data[] = {0x01, 0x02, 0x03, 0x04};

and then run this program as a prebuild step of your application (in your Makefile or whatever build system you are using), and generate the output into your source tree.

In that way the data would be compiled into your application and be available statically.

As I said, I'm not clear if this is the problem you are trying to solve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top