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

C 語言檔案操作工具庫完整實作:讀寫、複製、加解密

     編輯:關於C

模組設計目標

封裝常見檔案操作為可重用的 C 函式庫,包含:

  • 基本資訊查詢:行數、位元組大小
  • 整檔載入記憶體與關鍵字搜尋
  • 字串追加寫入、檔案複製
  • 單字元 XOR 加解密、字串金鑰加解密

所有函式統一回傳 int:成功 1,失敗 0(或負值表錯誤碼),並附帶詳細註解符合企業級編碼規範。

標頭檔 file.h 節錄

#ifndef _FILE_H_
#define _FILE_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>      // Sleep()
#include <crtdbg.h>       // 記憶體洩漏偵測

#pragma warning(disable:4996)  // 禁用 CRT 安全警告

// 取得檔案行數,失敗回傳 -1
extern int getFileRow(const char *path);
// 取得檔案大小(位元組),失敗回傳 -1
extern int getFileSize(const char *path);
// 載入檔案至記憶體 (pp 為全域靜態指標陣列),成功 1 失敗 0
extern int loadFile(const char *fPath, const int rowSize);
// 關鍵字搜尋並列印匹配行
extern int findStringByKeyword(const char *keyword, const int rowSize);
// 釋放 loadFile 配置的記憶體
extern void freeMemory(char **pp, const int rowSize);
// 字串寫入檔案,mode: 0 直接追加, 1 換行追加
extern int writeStr2File(const char *pFilePath, const char *pStr, int mode);
// 檔案複製
extern int copy(const char *pDestFile, const char *pOriginalFile);
// 單字元 XOR 加密/解密 (對稱)
extern int encryptFileByChar(const char *pDestFile, const char *pOriginalFile, const char ch);
extern int deCodeFileByChar(const char *pDestFile, const char *pOriginalFile, const char ch);
// 字串金鑰加密/解密 (循環 XOR)
extern char *str2EncryptString(char *pwdStr, char *str);
extern char *str2DecodedString(char *pwdStr, char *str);
// 整檔字串金鑰加解密
extern int encryptAndDecodeFileByString(const char *pDestFile,
                                        const char *pOriginalFile,
                                        const char *pwdString);

#endif

核心函式實作亮點

1. 取得行數 getFileRow

int getFileRow(const char *path) {
    FILE *pf = fopen(path, "r");
    if (!pf) return -1;
    int rows = 0;
    char buf[275];
    while (fgets(buf, sizeof(buf), pf)) ++rows;  // fgets 含換行,比 feof 更可靠
    fclose(pf);
    return rows;
}

※ 原碼使用 fgetc 讀行易出錯,已改為 fgets。

2. 載入檔案 loadFile

static char **pp = NULL;  // 檔案級靜態,配合 freeMemory 使用

int loadFile(const char *fPath, const int rowSize) {
    FILE *pf = fopen(fPath, "r");
    if (!pf) return 0;
    pp = (char **)malloc(sizeof(char *) * rowSize);
    for (int i = 0; i < rowSize; ++i) {
        char buf[275] = {0};
        fgets(buf, sizeof(buf), pf);
        int len = strlen(buf) + 1;
        pp[i] = (char *)malloc(len);
        strcpy(pp[i], buf);
        pp[i][len-1] = '\0';
    }
    fclose(pf);
    return 1;
}

3. XOR 單字元加解密 encryptFileByChar / deCodeFileByChar

加密與解密邏輯完全相同(XOR 對稱性),僅函式名稱不同以利語義區分:

int encryptFileByChar(const char *dst, const char *src, char ch) {
    FILE *fr = fopen(src, "rb"), *fw = fopen(dst, "wb");
    if (!fr || !fw) { if(fr)fclose(fr); if(fw)fclose(fw); return 0; }
    int len = getFileSize(src);
    char *buf = (char *)malloc(len);
    fread(buf, 1, len, fr);
    for (int i = 0; i < len; ++i) buf[i] ^= ch;
    fwrite(buf, 1, len, fw);
    free(buf); fclose(fr); fclose(fw);
    return 1;
}

4. 字串金鑰加密 str2EncryptString

採循環 XOR:str[i] ^= pwdStr[i % pwdLen],支援任意長度明文與金鑰。解密函式 str2DecodedString 邏輯完全相同。

5. 整檔字串金鑰加解密 encryptAndDecodeFileByString

int encryptAndDecodeFileByString(const char *dst, const char *src, const char *pwd) {
    FILE *fr = fopen(src, "r"), *fw = fopen(dst, "w");
    if (!fr || !fw) { if(fr)fclose(fr); if(fw)fclose(fw); return 0; }
    int len = getFileSize(src);
    char *buf = (char *)malloc(len + 1);
    for (int i = 0; i < len; ++i) buf[i] = fgetc(fr);
    buf[len] = '\0';
    str2EncryptString(pwd, buf);  // 就地加密
    for (int i = 0; i < len; ++i) fputc(buf[i], fw);
    free(buf); fclose(fr); fclose(fw);
    return 1;  // 原碼回傳 -1 疑為筆誤,已修正
}

使用範例

int main() {
    // 1. 載入並搜尋
    int rows = getFileRow("data.txt");
    loadFile("data.txt", rows);
    findStringByKeyword("error", rows);
    freeMemory(pp, rows);
    
    // 2. 複製與加密
    copy("backup.txt", "data.txt");
    encryptFileByChar("data.enc", "data.txt", 0x5A);
    deCodeFileByChar("data.dec", "data.enc", 0x5A);
    
    // 3. 字串金鑰加密
    encryptAndDecodeFileByString("data.enc2", "data.txt", "MySecretKey");
    encryptAndDecodeFileByString("data.dec2", "data.enc2", "MySecretKey");
    return 0;
}

注意事項與改進建議

  1. 緩衝區大小固定 275:若行長超過會截斷,建議動態分配或使用 getline (POSIX)。
  2. 全域靜態 pp 非執行緒安全,多執行緒環境下應改為呼叫者傳入指標。
  3. 錯誤處理:部分路徑 fclose(NULL) 會導致未定義行為,已在上方修正為先判斷指標。
  4. 編碼問題:Windows fopen 預設文字模式會轉換 \r\n,二進位檔案請用 "rb"/"wb"。
  5. 加密強度:XOR 僅適合簡易混淆,敏感資料請使用 AES 等標準演算法。

結語

本工具庫涵蓋 C 語言檔案操作最常見需求,代碼結構清晰、註解完整,適合直接整合至嵌入式、桌面或伺服器端專案。後續可擴充:目錄遞迴、非同步 I/O、壓縮/校驗碼等功能。

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