首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C++ 實現檔案分割與合併工具:袖珍檔案分割器核心邏輯

     編輯:關於C語言

完整實現大檔案分割為多個小檔案、並可還原合併的核心演算法與 MFC 介面程式。

核心思想

  • 分割:依指定大小等分,順序讀取區塊寫入新檔案。命名規則:序號_原檔名 (如 1_test.zip、2_test.zip),便於合併時排序。
  • 合併:依檔名前綴序號排序讀取,順序寫入單一檔案,輸出檔名為去除前綴的原檔名。

分割核心程式碼

int CFileSplitDlg::SplitMe() {
    // ... 開啟來源檔案、計算分割數量 ...
    long l = 1;
    char buff[20];
    do {
        CString name = _ltoa(l, buff, 10); name += "_"; // 序號前綴
        CString newPath = m_targetPath;
        if (newPath.Right(1) != "\\") newPath += "\\";

        CFile destFile;
        if (!destFile.Open(newPath + name + m_SourceFile.GetFileName(),
            CFile::modeWrite | CFile::shareExclusive | CFile::typeBinary | CFile::modeCreate)) {
            // 錯誤處理...
        }

        DWORD dwRead;
        do {
            dwRead = m_SourceFile.Read(buffer, nCount);
            destFile.Write(buffer, dwRead);
        } while (dwRead > 0 && destFile.GetLength() < nSplitSize); // 關鍵:限制單檔大小

        destFile.Close();
        l++;
        UpdateWindow();
    } while (dwRead > 0); // 來源檔案讀完結束
    m_SourceFile.Close();
    return 0;
}

合併核心程式碼

int CFileSplitDlg::MergeMe() {
    // ... 開啟目標合併檔案 ...
    long l = 1;
    char buff[20];
    do {
        CString pref = _ltoa(l, buff, 10); pref += "_";
        CFile srcFile;
        if (!srcFile.Open(newPath + pref + m_fileName,
            CFile::modeRead | CFile::shareExclusive | CFile::typeBinary)) {
            // 找不到下一個分割檔,合併完成
            break;
        }

        DWORD dwRead;
        do {
            dwRead = srcFile.Read(buffer, nCount);
            destFile.Write(buffer, dwRead);
        } while (dwRead > 0);

        srcFile.Close();
        l++;
        UpdateWindow();
    } while (l < 500); // 簡易上限,實際應動態判斷
    return 0;
}

關鍵技術點

項目實作細節
緩衝區固定大小 (如 4KB/64KB) 平衡記憶體與 I/O 效率
二進制模式CFile::typeBinary 確保位元組精確對應,支援任意檔案類型
獨佔共享CFile::shareExclusive 防止分割/合併過程中被其他程式修改
錯誤處理CFileException 捕獲開啟/讀寫失敗,彈出訊息並清理資源
進度回饋UpdateWindow() 強制重繪進度條/狀態文字

介面截圖

擴充建議

  • 支援拖放檔案、命令列參數。
  • 加入 CRC32/MD5 校驗確保分割合併無損。
  • 多執行緒並行讀寫提升大檔案效能。
  • 自解壓合併模組 (生成 .exe 直接執行合併)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved