2012-09-12 107 views
1

使用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; 

我想知道如何做到這一點,因爲我認爲這將是必不可少的局域網文件共享應用程序。我確定有更高級別的API用於使用套接字發送文件,但我想知道這些API實際上是如何工作的。

我可以逐位提取,存儲和寫入文件,因此輸入和輸出文件之間沒有差異嗎?感謝您的幫助,非常感謝。

+5

您需要爲流構造函數的'openmode'參數傳遞'std :: ios :: binary'。將一個流的內容批量複製到另一個流的最佳方式是new_file << file.rdbuf();'。 – ildjarn

+0

'std:string'是文本 - 不是二進制數據。二進制數據可以用'vector '或'basic_string '表示。試試看。 – Linuxios

+2

@Linuxios:'std :: string'可以包含任何'char'值,所以它能夠保存二進制數據;這裏的問題是流執行結束轉換。 – ildjarn

回答

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<<爲格式化數據,除了當像上面使用它。

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; 
} 

雖然,你會更好做一個字符緩衝區,並使用ifstream::read/ofstream::write閱讀和寫一次塊。

相關問題