首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 文件讀寫二進制流:完整示範 (含十六進制輸出)

     編輯:程式設計綜合問答

需求:任意文件 → 位元組陣列 → 十六進制字串顯示 → 還原文件。核心 API:`fread`/`fwrite` + 動態記憶體。

完整可編譯代碼 (C/C++ 通用)

#include 
#include 
#include 

// 讀取文件到位元組陣列,回傳長度 (呼叫者負責 free)
size_t ReadFileToBuffer(const char* filename, unsigned char** outBuf) {
    FILE* fp = fopen(filename, "rb");
    if (!fp) return 0;
    fseek(fp, 0, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    if (size <= 0) { fclose(fp); return 0; }
    *outBuf = (unsigned char*)malloc(size);
    size_t read = fread(*outBuf, 1, size, fp);
    fclose(fp);
    return read;
}

// 將位元組陣列寫入文件
bool WriteBufferToFile(const char* filename, const unsigned char* buf, size_t len) {
    FILE* fp = fopen(filename, "wb");
    if (!fp) return false;
    fwrite(buf, 1, len, fp);
    fclose(fp);
    return true;
}

// 列印十六進制 (每行 16 位元組)
void PrintHex(const unsigned char* buf, size_t len) {
    for (size_t i = 0; i < len; ++i) {
        printf("%02X ", buf[i]);
        if ((i + 1) % 16 == 0) printf("\n");
    }
    printf("\n");
}

int main() {
    unsigned char* data = nullptr;
    size_t len = ReadFileToBuffer("test.zip", &data);
    if (len == 0) { printf("讀取失敗\n"); return 1; }

    printf("檔案大小: %zu bytes\n", len);
    PrintHex(data, len);           // 輸出十六進制
    WriteBufferToFile("new_test.zip", data, len); // 還原
    free(data);
    printf("還原完成\n");
    return 0;
}

關鍵細節

  • "rb"/"wb" 二進制模式防止 Windows 換行符轉換 (`\n` ↔ `\r\n`)。
  • `ftell` 回傳 `long`,大於 2GB 檔案需用 `_ftelli64` / `fseeko64`。
  • 記憶體分配檢查 `malloc` 回傳值,生產碼需加錯誤處理。
  • 十六進制輸出用 `%02X` 確保兩位大寫,`unsigned char` 避免符號擴展。

C++ 現代寫法 (RAII + vector)

#include 
#include 
#include 
#include 

std::vector<unsigned char> ReadFile(const std::string& path) {
    std::ifstream in(path, std::ios::binary | std::ios::ate);
    std::streamsize size = in.tellg();
    in.seekg(0);
    std::vector<unsigned char> buf(size);
    in.read(reinterpret_cast<char*>(buf.data()), size);
    return buf;
}

void WriteFile(const std::string& path, const std::vector<unsigned char>& buf) {
    std::ofstream out(path, std::ios::binary);
    out.write(reinterpret_cast<const char*>(buf.data()), buf.size());
}

兩版本均可實現「文件 ↔ 位元組流 ↔ 文件」無損轉換,適合網路傳輸、資料庫 Blob 存儲、加密前處理等場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved