简体   繁体   中英

C++ Stand-alone executable

I'm writing a program in C++ that requires a file to be in the current directory, but I want to distribute it as one executable. Love2D uses a distribution method for games where you create a .love file and use cat to combine the love2d binary and your .love file (eg. cat love2d awesomegame.love > awesomegame ). How can I write my program so it can use the information at the end of itself, and extract that out into a file.

--- Update ---

Thanks to all the wonderful help from @Dawid, I have got this working in a cleaner method than I originally suggested (see my answer if you want to do it that way). Here is my final source code:

#include <fstream>
#include "ncat.h"

using namespace std;

int main () {
    ofstream ofile("ncat.exe", ios_base::out | ios_base::binary);
    for (unsigned long i = 0 ; i < ncat_exe_len; ++i) ofile << ncat_exe[i];
    ofile.close();
    return 0;
}

Here's the (binary) file I'm using: https://www.dropbox.com/s/21wps8usaqgthah/ncat.exe?dl=0

You can use xxd tool. It can dump binary as hex in C style include header.

eg.

> echo test > a
> xxd -i a > a.h
> cat a.h
unsigned char a[] = {
  0x74, 0x65, 0x73, 0x74, 0x0a
};
unsigned int a_len = 5;

then simply include header and use a and a_len .

Example:

before build:

xxd -i _file_name_ > _file_name_.h

in program:

#include "_file_name_.h"
void foo() {
    std::ofstream file ("output.txt", std::ios_base::out | std::ios_base::binary);
    file << _file_name_; // I believe the array will be named after source file
}

When your program starts, check if the file exists and is correct. If it is not present or incorrect, write out the contents of the file from a variable ( structure ) to the file you want.

I figured it out:

#include <string>
#include <fstream>

string OUTPUT_NAME = "output.txt";

using namespace std;

int main(int argc, char *argv[]) {
    bool writing = false;
    string line;

    ofstream ofile;
    ofile.open(OUTPUT_NAME);
    ifstream ifile (argv[0]);
    if (ifile.is_open()) {
        while (getline(ifile, line)) {
            if (writing) {
                ofile << line << endl;
            } else if (line == "--") {
                writing = true;
            }
        }
    }
    ofile.close();
}

To create the final binary, copy the original binary, then type echo -e "\\n--" >> _binary_name_ and then cat _file_name_ >> _binary_name_

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM