需求:讀取源文件,移除重複行(判斷標準:1) 字符完全相同;2) 去除空格與換行後相同),並將結果寫入目標文件,同時刪除空行。
fgets)。RmNewLine)、移除所有空格(RemoveSpaceInStr)。IsInList),不存在則插入鏈表尾部。WriteToFile)。ClearList)。
typedef struct T_FileInfoStruct {
UINT8 szContentLine[256];
struct T_FileInfoStruct *pNext;
} T_FileInfo;
UINT32 IsInList(T_FileInfo *head, UINT8 *line) {
if (!head || !line) return 0;
while (head) {
if (strncmp(line, head->szContentLine, strlen(line)) == 0) return 1;
head = head->pNext;
}
return 0;
}
void RemoveSpaceInStr(UINT8 *str, UINT32 len) {
UINT8 buf[256], res[256];
memcpy(buf, str, len);
UINT32 dst = 0;
for (UINT32 src = 0; src < strlen(buf); src++) {
if (buf[src] != ' ') res[dst++] = buf[src];
}
res[dst] = '\0';
memcpy(str, res, len);
}
在 WriteToFile 中,每次寫入前必須 memset(szContentBuf, 0, sizeof(szContentBuf)) 清空緩衝區,否則殘留數據會導致輸出錯誤。
gcc -g -o RemoveRepeatLine RemoveRepeatLine.c
./RemoveRepeatLine
源文件 TestFile.txt → 目標文件 ResultFile.txt,成功去除重複行與空行。
getenv("HOME")),實際部署時應改為配置文件或命令行參數指定路徑。