c++独立可执行文件

C++ Stand-alone executable

本文关键字:可执行文件 独立 c++      更新时间:2023-10-16

我正在用c++编写一个程序,该程序需要一个文件位于当前目录中,但我想将其作为一个可执行文件分发。Love2D使用游戏的分发方法,您创建一个.love文件,并使用cat来组合love2d二进制文件和您的.love文件(例如。cat love2d awesomegame.love > awesomegame)。我该如何编写程序,使其能够使用其末尾的信息,并将其提取到文件中呢?

—Update—

感谢@ david的所有精彩帮助,我已经用比我最初建议的更干净的方法工作了(如果你想这样做,请参阅我的答案)。这是我最后的源代码:

#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;
}

下面是我使用的(二进制)文件:https://www.dropbox.com/s/21wps8usaqgthah/ncat.exe?dl=0

您可以使用xxd工具。它可以将二进制文件转储为C格式的十六进制。

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

则只需包含header并使用aa_len

的例子:构建前

:

xxd -i _file_name_ > _file_name_.h
在计划:

#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
}

程序启动时,检查文件是否存在并且正确。如果不存在或不正确,则将文件的内容从变量(结构)写入所需的文件。

我明白了:

#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();
}
要创建最终的二进制文件,复制原始的二进制文件,然后键入echo -e "n--" >> _binary_name_cat _file_name_ >> _binary_name_
相关文章: