首頁 > 後端開發 > C++ > 如何在C中正確讀取和寫入整個二進位檔案?

如何在C中正確讀取和寫入整個二進位檔案?

Linda Hamilton
發布: 2025-01-03 14:25:40
原創
524 人瀏覽過

How to Correctly Read and Write Entire Binary Files in C  ?

讀取和寫入二進位檔案

當嘗試將二進位檔案讀入緩衝區並隨後將緩衝區寫入另一個檔案時,它是使用適當的方法至關重要。提供的程式碼片段遇到錯誤,緩衝區僅捕獲文件第一行中的幾個 ASCII 字符,無法檢索其全部內容。

要解決這個問題,有兩種建議的方法:

  1. 使用 C方法:

    利用 C的流迭代功能,以下程式碼有效地將輸入二進位檔案的內容複製到輸出檔案:

    #include <fstream>
    #include <iterator>
    #include <algorithm>
    
    int main()
    {
        std::ifstream input("C:\Final.gif", std::ios::binary);
        std::ofstream output("C:\myfile.gif", std::ios::binary);
    
        std::copy(
            std::istreambuf_iterator<char>(input),
            std::istreambuf_iterator<char>(),
            std::ostreambuf_iterator<char>(output));
    }
    登入後複製
  2. 使用Buffer進行修改:

    如果資料需要為了修改目的而儲存在緩衝區中,可以採用以下方法:

    #include <fstream>
    #include <iterator>
    #include <vector>
    
    int main()
    {
        std::ifstream input("C:\Final.gif", std::ios::binary);
    
        // Copies all data into buffer
        std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
    }
    登入後複製

透過實現這些技術,程式碼將成功地將整個二進位檔案讀入緩衝區或直接讀取到輸出檔案中,確保準確的資料傳輸和操作。

以上是如何在C中正確讀取和寫入整個二進位檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板