C++ 去除重复的文本
时间: 2023-11-14 15:15:02 浏览: 31
在C语言中去除重复的文本可以通过以下步骤实现:
1. 读取文本文件中的每一行数据并存储到一个字符数组中。
2. 对于每一行数据,使用一个哈希表或者集合来判断该行数据是否已经出现过。
3. 如果该行数据没有出现过,则将其输出到一个新的文本文件中,并将其添加到哈希表或者集合中。
4. 最后关闭原始文件和新文件。
下面是一个示例代码,可以实现去除重复行的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s input_file output_file\n", argv[0]);
return 1;
}
char *input_file = argv[1];
char *output_file = argv[2];
FILE *in_fp = fopen(input_file, "r");
if (in_fp == NULL) {
printf("Error opening file %s\n", input_file);
return 1;
}
FILE *out_fp = fopen(output_file, "w");
if (out_fp == NULL) {
printf("Error creating file %s\n", output_file);
return 1;
}
char line[MAX_LEN];
int line_count = 0;
// 使用哈希表来存储出现过的行数据
int hash_table[100000] = {0};
while (fgets(line, MAX_LEN, in_fp) != NULL) {
line_count++;
// 计算哈希值
int hash_value = 0;
for (int i = 0; i < strlen(line); i++) {
hash_value = (hash_value * 31 + line[i]) % 100000;
}
// 如果该行数据已经出现过,则跳过
if (hash_table[hash_value] == line_count) {
continue;
}
// 将该行数据输出到新文件中
fprintf(out_fp, "%s", line);
hash_table[hash_value] = line_count;
}
fclose(in_fp);
fclose(out_fp);
return 0;
}
```