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

文件分割與合併工具核心算法實現:大文件多盤存儲解決方案

     編輯:VC++

應用場景

大文件需跨多張軟盤/移動介質傳輸,或受限於單文件大小上限(如 FAT32 4GB)時,需將文件等分切割,傳輸後合併還原。

核心設計思想

  • 分割:按指定塊大小順序讀取源文件,寫入命名為 序號_原文件名 的目標文件(如 1_test.zip, 2_test.zip...)。
  • 合併:按序號順序讀取分割文件,順序寫入單一目標文件,還原原始內容。

分割核心代碼 (SplitMe)

int CFileSpltDlg::SplitMe() {
    // ... 打開源文件 m_SourceFile, 獲取分割大小 newlen ...
    long l = 1; // 文件序號
    char buff[20];
    DWORD dwRead;
    BYTE buffer[4096];
    CFileException ex;

    do {
        // 構建目標文件名: 1_原文件名
        _ltoa(l, buff, 10);
        CString name = buff; name += _T("_");
        CString newpath = m_targetpath;
        if (newpath.Right(1) != _T("\\")) newpath += _T("\\");

        CFile destFile;
        if (!destFile.Open(newpath + name + m_SourceFile.GetFileName(),
                           CFile::modeWrite | CFile::shareExclusive | CFile::typeBinary | CFile::modeCreate, &ex)) {
            ex.ReportError(); m_SourceFile.Close(); return 1;
        }

        // 循環讀寫直到達到分割大小或文件結束
        do {
            dwRead = m_SourceFile.Read(buffer, sizeof(buffer));
            if (dwRead > 0) destFile.Write(buffer, dwRead);
        } while (dwRead > 0 && destFile.GetLength() < newlen);

        destFile.Close();
        l++;
        UpdateWindow(); // 刷新進度
    } while (dwRead > 0); // 源文件讀完結束

    m_SourceFile.Close();
    return 0;
}

合併核心代碼 (MergeMe)

int CFileSpltDlg::MergeMe() {
    // ... 打開目標文件 destFile, 確定源目錄 newpath 與原文件名 m_filename ...
    long l = 1;
    char buff[20];
    DWORD dwRead;
    BYTE buffer[4096];
    CFileException ex;

    do {
        _ltoa(l, buff, 10);
        CString pref = buff; pref += _T("_");
        CString name = newpath + pref + m_filename;

        CFile srcFile;
        if (!srcFile.Open(name, CFile::modeRead | CFile::shareExclusive | CFile::typeBinary, &ex)) {
            // 文件不存在視為合併結束
            destFile.Close(); return 0;
        }

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

        srcFile.Close();
        l++;
        UpdateWindow();
    } while (l < 500); // 安全上限,防死循環

    return 0;
}

關鍵點與改進建議

  • 文件命名規則:前綴數字 + 下劃線 + 原文件名,保證自然排序即為正確順序。
  • 緩衝區大小:示例用 4KB,實際建議 64KB~1MB 提升 I/O 效率。
  • 異常處理:磁盤滿、讀寫錯誤、文件缺失需完善錯誤碼返回與用戶提示。
  • 校驗機制:生產級工具應增加 CRC32/MD5 校驗,確保分割文件完整性與合併正確性。
  • 界面交互:進度條、取消按鈕、多線程分割避免 UI 凍結。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved