【发布时间】:2022-11-27 15:50:13
【问题描述】:
我想多次复制 exe 文件本身。
我尝试了以下代码:
#include <fstream>
#include <string>
int main() {
std::ifstream from("main.exe", std::ios::binary);
auto buf { from.rdbuf() };
for(int x { 0 }; x <= 10; ++x) {
std::string name { "main" + std::to_string(x) + ".exe" };
std::ofstream out(name, std::ios::binary);
out << buf;
out.close();
}
from.close();
return 0;
}
但它没有像我预期的那样工作(它不会重复复制可执行文件。请参阅以下屏幕截图中的大小列):
我该如何解决这个问题?
【问题讨论】:
-
这没有解决问题,但无需致电
out.close();或from.close();。析构函数会这样做。 -
如果我是治标不治本(我现在没有精力认真分析代码),我会把
main的前两行移到循环内。 -
声明
out << buf;将提炼来自buf的所有数据,没有留下任何东西。 -
您永远不会检查打开文件是否成功。打开后添加
if(!from) { std::cout << std::strerror(errno) << '\n'; return 1; }。