[英]Why can't I copy executables like this?
使用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的實際工作方式。
我可以逐位提取,存儲和寫入文件,這樣輸入和輸出文件之間就不會有差異嗎? 多謝您的協助,不勝感激。
不知道為什么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<<
用於格式化的數據, 除非像上述那樣使用。
基本而言:
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
讀取和寫入塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.