[英]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. 我正在用C ++编写一个程序,该程序要求文件位于当前目录中,但是我想将其作为一个可执行文件分发。 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
). Love2D对游戏使用分发方法,在该游戏中,您创建一个
.love
文件,并使用cat
组合love2d
二进制文件和您的.love
文件(例如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). 感谢@Dawid的所有出色帮助,使我的工作方式比我最初建议的更干净(如果您想这样做,请参阅我的回答)。 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 这是我正在使用的(二进制)文件: https : //www.dropbox.com/s/21wps8usaqgthah/ncat.exe?dl=0
You can use xxd
tool. 您可以使用
xxd
工具。 It can dump binary as hex in C style include header. 它可以以C样式的include标头中的十六进制形式转储二进制文件。
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
. 然后只需包含标头并使用
a
和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_
要创建最终的二进制文件,请复制原始二进制文件,然后键入
echo -e "\\n--" >> _binary_name_
,然后输入cat _file_name_ >> _binary_name_
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.