使用C++ <fstream>,复制文本文件非常简单:
#include <fstream>
int main() {
std::ifstream file("file.txt");
std::ofstream new_file("new_file.txt");
std::string contents;
// Store file contents in string:
std::getline(file, contents);
new_file << contents; // Write contents to file
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是当您对可执行文件执行相同操作时,输出可执行文件实际上不起作用.也许std :: string不支持编码?
我希望我可以做类似下面的事情,但文件对象是一个指针,我无法取消引用它(运行以下代码创建new_file.exe实际上只包含某些内存地址):
std::ifstream file("file.exe");
std::ofstream new_file("new_file.exe");
new_file << file;
Run Code Online (Sandbox Code Playgroud)
我想知道如何做到这一点,因为我认为它在LAN文件共享应用程序中是必不可少的.我确信有更高级别的API用于发送带套接字的文件,但我想知道这些API实际上是如何工作的.
我可以逐位提取,存储和写入文件,因此输入和输出文件之间没有差异吗?感谢您的帮助,非常感谢.
不确定为什么ildjarn发表了评论,但为了得到答案(如果他发布了答案,我会删除它).基本上,您需要使用无格式的读写.getline格式化数据.
int main()
{
std::ifstream in("file.exe", std::ios::binary);
std::ofstream out("new_file.exe", std::ios::binary);
out << in.rdbuf();
}
Run Code Online (Sandbox Code Playgroud)
从技术上讲,operator<<是用于格式化数据,除非像上面那样使用它.