简体   繁体   中英

How to compare strings of two files?

I am a new c-language programmer.

I have got two files. One consists of lines like:

84:1b:5e:a8:bf:7f

00:8e:f2:c0:13:cc

Another consists of lines like:

00-22-39

8C-FD-F0

My question is how can I using C language compare first half of line in the first file with a line in the second file? Like: is 84:1b:5e equals to 8C-FD-F0 ? I know the way to create an arrays to store those lines for the further comparison. But do I really need to create arrays?

PS: comparison is case-insensitive

You haven't been very clear about what rules constitute a match. But if you want to compare the byte values, then you need to parse each line, converting it to those byte values.

You could use variations of strtok() to get the values from each line. However, a variation of sscanf() might be easier. Once you have the binary values from each file, then you can compare them.

Read the second file completely and store the contents in a sorted array. Then for each line read from the first file, binary search the sorted array to locate the match.

Implementation is below. It compiles with gcc.

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

int cmp(const void * s1, const void * s2)
{
    return strcasecmp(*(char **)s1, *(char **)s2);
}

int cmp_half(const char * s1, const char * s2)
{
    int i;
    for (i = 0; i < 3; i++)
    {
        int res = strncasecmp((char *)s1+i*3, (char *)s2+i*3, 2);
        if (res != 0) return res;
    }

    return 0;
}

char * line[1024];
int n = 0;

int search(const char * s)
{
    int first, last, middle;
    first = 0;
    last = n - 1;
    middle = (first+last)/2;

    while( first <= last )
    {
        int res = cmp_half(s, line[middle]);
        if (res == 0) return middle;
        if (res > 0)
            first = middle + 1;    
        else
            last = middle - 1;

        middle = (first + last)/2;
    }
    return -1;
}

int main()
{
    FILE * f1, * f2;
    char * s;
    char buf[1024*1024], text[1024];

    f1 = fopen("file1.txt", "rt");
    f2 = fopen("file2.txt", "rt");

    s = buf;
    while (fgets(s, 1024, f2) != NULL)
    {
        line[n] = s;
        s = s+strlen(s)+1;
        n++;
    }

    qsort(line, n, sizeof(char *), cmp);

    while (fgets(text, 1024, f1) != NULL)
    {
    text[strlen(text)-1] = 0;
        int idx = search(text);
        if (idx >= 0)
        {
            printf("%s matched %s\n", text, line[idx]);
        }
        else
        {
            printf("%s not matched\n", text);
        }
    }

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM