使用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;
}
但是当您对可执行文件执行相同操作时,输出可执行文件实际上不起作用。也许std :: string不支持编码?
我希望我可以执行以下操作,但文件对象是一个指针,我无法取消引用它(运行以下代码创建new_file.exe,实际上只包含某些内存地址) :
std::ifstream file("file.exe");
std::ofstream new_file("new_file.exe");
new_file << file;
我想知道如何做到这一点,因为我认为它在LAN文件共享应用程序中是必不可少的。我确信有更高级别的API用于发送带套接字的文件,但我想知道这些API实际上是如何工作的。
我可以逐位提取,存储和写入文件,因此输入和输出文件之间没有差异吗?感谢您的帮助,非常感谢。
答案 0 :(得分:6)
不确定为什么ildjarn将其作为评论,但要使其成为答案(如果他发布了答案,我会删除它)。基本上,您需要使用无格式读写。 getline
格式化数据。
int main()
{
std::ifstream in("file.exe", std::ios::binary);
std::ofstream out("new_file.exe", std::ios::binary);
out << in.rdbuf();
}
从技术上讲,operator<<
用于格式化数据,除了,就像上面那样使用它。
答案 1 :(得分:2)
用非常基本的术语来说:
using namespace std;
int main() {
ifstream file("file.txt", ios::in | ios::binary );
ofstream new_file("new_file.txt", ios::out | ios::binary);
char c;
while( file.get(c) ) new_file.put(c);
return 0;
}
尽管如此,你最好制作一个char缓冲区并使用ifstream::read
/ ofstream::write
一次读取和写入块。