在这个问题中: Detecting duplicate lines on file using c 我可以检测到重复的行,但我们如何从我们的文件中删除此行?使用C删除文件中的所有重复行C
谢谢。
编辑:要添加我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct somehash {
struct somehash *next;
unsigned hash;
char *mem;
};
#define THE_SIZE 100000
struct somehash *table[THE_SIZE] = { NULL,};
struct somehash **some_find(char *str, unsigned len);
static unsigned some_hash(char *str, unsigned len);
int main (void)
{
char buffer[100];
struct somehash **pp;
size_t len;
FILE * pFileIn;
FILE * pFileOut;
pFileIn = fopen("in.csv", "r");
pFileOut = fopen("out.csv", "w+");
if (pFileIn==NULL) perror ("Error opening input file");
if (pFileOut==NULL) perror ("Error opening output file");
while (fgets(buffer, sizeof buffer, pFileIn)) {
len = strlen(buffer);
pp = some_find(buffer, len);
if (*pp) { /* found */
fprintf(stderr, "Duplicate:%s\n", buffer);
}
else
{ /* not found: create one */
fprintf(stdout, "%s", buffer);
fprintf(pFileOut, "%s", buffer);
*pp = malloc(sizeof **pp);
(*pp)->next = NULL;
(*pp)->hash = some_hash(buffer,len);
(*pp)->mem = malloc(1+len);
memcpy((*pp)->mem , buffer, 1+len);
}
}
return 0;
}
struct somehash **some_find(char *str, unsigned len)
{
unsigned hash;
unsigned short slot;
struct somehash **hnd;
hash = some_hash(str,len);
slot = hash % THE_SIZE;
for (hnd = &table[slot]; *hnd ; hnd = &(*hnd)->next) {
if ((*hnd)->hash != hash) continue;
if (strcmp((*hnd)->mem , str)) continue;
break;
}
return hnd;
}
static unsigned some_hash(char *str, unsigned len)
{
unsigned val;
unsigned idx;
if (!len) len = strlen(str);
val = 0;
for(idx=0; idx < len; idx++) {
val ^= (val >> 2)^(val << 5)^(val << 13)^str[idx]^0x80001801;
}
return val;
}
但在输出文件中,我们总能得到第一次出现!
编辑2:澄清:目的是在输入文件中查找所有重复项。当输入中有多条线的实例时,该线不应出现在输出的所有处。意图不仅仅是删除的重复的行,因此每行只出现一次,而是删除全部行的实例(如果该行在输入中重复)。
另一方面,SHA256哈希长度为32字节,可能比平均线长度长,*计算*它们将在'O(N)'项上大量增加常量。 – zwol 2012-04-17 23:14:10
@Zack:好点。见编辑的答案。 – 2012-04-17 23:46:09
@JerryCoffin:谢谢,我发布了我的代码,问题是始终将第一个匹配项添加到文件中,导致我们第一次对它进行哈希处理,我们需要将其插入到文件中。 – iPadDevloperJr 2012-04-18 18:12:57