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

C++Builder 設計檔案分割器:二進位讀寫分割與合併、進度顯示、多執行緒雛形

     編輯:VC 教學

原理

所有檔案本質為二進位位元組流。分割:依指定大小 (KB) 切塊寫出 `檔名.001`、`.002`... 合併:依序讀入各分割檔寫回目標檔。

介面元件

  • `TDriveComboBox`、`TDirectoryListBox`、`TFileListBox` (Win3.1 頁) 選擇來源檔。
  • `TComboBox` 輸入分割大小 (KB)。
  • `TEdit` 顯示來源路徑、目標前綴、預估分割數。
  • `TListBox` 列出將產生的分割檔名。
  • `TProgressBar` 顯示進度。
  • `TBitBtn`:分割、合併、瀏覽、取消、關閉。

核心變數 (私有)


int FileHandle;      // 檔案控制碼
int FileLength;      // 來源檔大小
int NumParts;        // 分割數
int BytesRead;       // 已讀位元組
char *pszBuffer;     // 緩衝區指標
int BufSize;         // 緩衝區大小 (分割大小 * 1024)

分割邏輯 (FileListBox1Change 更新 UI)


void __fastcall TForm1::FileListBox1Change(TObject *Sender)
{
    Edit1->Text = FileListBox1->FileName;
    Edit3->Text = ChangeFileExt(FileListBox1->FileName, ".000"); // 目標前綴
    BufSize = ComboBox1->Text.ToInt() * 1024;
    FileHandle = FileOpen(Edit1->Text, fmOpenRead);
    FileLength = FileSeek(FileHandle, 0, 2); // 移至末尾取得大小
    FileClose(FileHandle);
    NumParts = FileLength / BufSize + 1;
    Edit4->Text = "分割成 " + IntToStr(NumParts) + " 個檔案";
    ListBox1->Clear();
    for (int i=1; i<=NumParts; i++)
        ListBox1->Items->Add(ChangeFileExt(Edit3->Text, "." + IntToStr(i).Format("%0.3d")));
}

分割執行 (含進度更新)


void __fastcall TForm1::BtnSplitClick(TObject *Sender)
{
    FileHandle = FileOpen(Edit1->Text, fmOpenRead);
    pszBuffer = new char[BufSize];
    ProgressBar1->Max = NumParts;
    for (int i=1; i<=NumParts; i++) {
        BytesRead = FileRead(FileHandle, pszBuffer, BufSize);
        int hOut = FileCreate(ListBox1->Items->Strings[i-1]);
        FileWrite(hOut, pszBuffer, BytesRead);
        FileClose(hOut);
        ProgressBar1->Position = i;
        Application->ProcessMessages(); // 保持 UI 響應
    }
    delete[] pszBuffer;
    FileClose(FileHandle);
    ShowMessage("分割完成!");
}

合併邏輯

反向操作:依序 `FileOpen` 各分割檔 → `FileRead`/`FileWrite` 至目標檔 → 進度更新。

改進方向

  • 移至背景執行緒 (`TThread`),避免 UI 凍結。
  • 加入 CRC32/MD5 校驗確保完整性。
  • 支援拖放檔案、關聯 `.001` 雙擊自動合併。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved