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

C 語言實現文件去重:鏈表存儲+空格換行符清洗

     編輯:關於C

需求描述

讀取源文本文件,去除完全重複的行(含空格、換行符差異視為相同),並將結果寫入目標文件。空行同樣被過濾。

整體流程設計

  1. 逐行讀取源文件(fgets);
  2. 清洗每行:去除尾部換行符、刪除所有空格;
  3. 若清洗後非空,遍歷鏈表判斷是否已存在;
  4. 不存在則插入鏈表尾部;
  5. 讀取完畢,遍歷鏈表寫入目標文件(每行加換行符);
  6. 釋放鏈表內存。

關鍵數據結構

typedef struct FileNode {
    char content[256];
    struct FileNode *next;
} FileNode;

核心函數實現

去除換行符

void rmNewline(char *str) {
    int len = strlen(str);
    while (len > 0 && (str[len-1] == '\n' || str[len-1] == '\r'))
        str[--len] = '\0';
}

刪除字符串中所有空格

void removeSpaces(char *str) {
    char *dst = str;
    for (char *src = str; *src; ++src)
        if (*src != ' ') *dst++ = *src;
    *dst = '\0';
}

鏈表查重

int existsInList(FileNode *head, const char *line) {
    for (FileNode *p = head; p; p = p->next)
        if (strcmp(p->content, line) == 0) return 1;
    return 0;
}

插入鏈表尾部

FileNode* appendNode(FileNode **head, FileNode **tail, const char *line) {
    FileNode *node = malloc(sizeof(FileNode));
    if (!node) return NULL;
    strcpy(node->content, line);
    node->next = NULL;
    if (!*head) *head = *tail = node;
    else { (*tail)->next = node; *tail = node; }
    return node;
}

寫入文件並清理

void writeAndFree(FileNode *head, const char *outPath) {
    FILE *fp = fopen(outPath, "w");
    if (!fp) return;
    for (FileNode *p = head; p; p = p->next) {
        fprintf(fp, "%s\n", p->content);
    }
    fclose(fp);
    // 釋放鏈表
    while (head) {
        FileNode *tmp = head;
        head = head->next;
        free(tmp);
    }
}

主程序邏輯

int main() {
    const char *inPath = "TestFile.txt";
    const char *outPath = "ResultFile.txt";
    FILE *fp = fopen(inPath, "r");
    if (!fp) return 1;

    FileNode *head = NULL, *tail = NULL;
    char line[256];

    while (fgets(line, sizeof(line), fp)) {
        rmNewline(line);
        removeSpaces(line);
        if (strlen(line) == 0) continue;
        if (!existsInList(head, line))
            appendNode(&head, &tail, line);
    }
    fclose(fp);
    writeAndFree(head, outPath);
    return 0;
}

運行示例

# TestFile.txt
ABCD EFGH
abcd
AB CD
abcd
12345

# ResultFile.txt
ABCDEFGH
abcd
12345

工程化補充說明

  • 內存安全:malloc 後檢查空指針;strcpy 目標緩衝區足夠大(256);
  • 緩衝區清零:寫入前 memset(buf, 0, sizeof(buf)) 防止殘留數據;
  • 大文件優化:若行數極大,鏈表查重 O(n²) 過慢,可改用哈希表(如 uthash)實現 O(1) 平均查找;
  • 跨平台換行:同時處理 \n 和 \r\n。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved