【问题标题】:C++ Stand-alone executableC++ 独立可执行文件
【发布时间】:2015-10-13 23:37:21
【问题描述】:

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

--- 更新---

感谢@Dawid 提供的所有出色帮助,我已经以一种比我最初建议的更简洁的方式工作(如果你想这样做,请参阅我的回答)。这是我的最终源代码:

#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

【问题讨论】:

  • 非常,非常小心。

标签: c++ linux file


【解决方案1】:

您可以使用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;

然后简单地包含标题并使用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
}

【讨论】:

  • 如何在我的程序中使用它?
  • @Person:通过将a[] 写入文件?
  • 我以为程序会使用变量 a 作为字符串流。
  • 这很好,除了以下划线开头的名称是保留的,而且这个变量定义在技术上不属于头文件,因为您不能将它包含到要链接的多个翻译单元中在一起。
  • @PSkocik: 1) @Person 确实提供了他如何使用_file_name_ 执行此操作的示例,所以我保持这个约定。 2) extern unsigned char a[]; extern int a_len; 和管道 xxd 输出到 cpp 文件,如果需要的话。发挥想象力吧。
【解决方案2】:

当你的程序启动时,检查文件是否存在并且正确。如果它不存在或不正确,则将文件的内容从变量(结构)写出到您想要的文件中。

【讨论】:

  • 我需要的文件是另一个二进制文件。将其复制到变量中会很麻烦。
【解决方案3】:

我想通了:

#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--" &gt;&gt; _binary_name_,然后输入cat _file_name_ &gt;&gt; _binary_name_

【讨论】:

  • @JeffS:不是为了自我回答。这在the relevant help page 上有明确解释。
  • 我不明白这是如何工作的。你正在破坏你的二进制文件。没有?
  • 是的,他正在用"--" 标记可执行代码的结尾,然后在文件末尾附加二进制文件作为原始数据。然后在运行时他读取二进制文件本身并在-- 标记转储内容以输出之后。很聪明。
猜你喜欢
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多