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