在C中重复消除

时间:2014-05-27 20:23:18

标签: c file struct duplicates double-elimination

我正在尝试从clients.txt(有7个名字和姓氏,其中一些重复)中进行重复删除。在文件的末尾,它将输出写入output.dat文件。我在编译期间没有收到任何错误,但是当我尝试运行它时,它会让#34; 003.exe停止工作"错误。 (003.c是C项目名称)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct names
{
    char name[25];
    char surname[25];
};


int main()
{
    int i, j;
    char a[1] = {""};
    struct names name[200];
    FILE *file;
    FILE *file2;
    file = fopen("clients.txt", "r");
    if (ferror(file))
    {
        printf ("File could not be opened");
    }

    while (fscanf(file, "%s", a) == 2)
    {
        i = 0;
        fscanf(file, "%s %s", name[i].name, name[i].surname);
        i++;
    }
    for (i = 0; i < 200; i++)
    {
        for (j = 0; j < 200; j++)
        {
            if (i != j && strcmp(name[i].name, name[j].name) == 0 && strcmp(name[i].surname, name[j].surname) == 0 )
            {
                strcpy(name[j].name, a);
                strcpy(name[j].surname, a);
            }
        }
    }
    fclose(file);
    file2 = fopen("output.dat", "w");
    {
        for (i = 0; i < 200; i++)
        {
            if ( strcmp(name[i].name, "") == 1 )
            {
                fprintf(file, "%s %s\n", name[i].name, name[i].surname);
            }
        }
    }
    fclose(file2);

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct names {
    char name[25];
    char surname[25];
};

int isEqual(struct names *a, struct names *b){
    return strcmp(a->name, b->name) == 0 && strcmp(a->surname, b->surname)==0;
}

int main(){
    int i, j;
    struct names name[200], a;
    FILE *file;

    file = fopen("clients.txt", "r");
    if (!file){//ferror can't use to fopen
        printf ("File could not be opened");
        return -1;
    }

    i=0;
    while (fscanf(file, "%24s %24s", a.name, a.surname) == 2){
        int dup = 0;
        for(j=0; j < i ;++j){
            if(dup=isEqual(&a, &name[j]))
                break;
        }
        if(!dup)//!dup && i<200
            name[i++] = a;
    }
    fclose(file);

    file = fopen("output.dat", "w");
    for (j = 0; j < i; ++j){
        fprintf(file, "%s %s\n", name[j].name, name[j].surname);
    }
    fclose(file);

    system("pause");
    return 0;
}