just ME
just ME

Reputation: 1827

compare two files c code

I need to compare two files line by line. One of the files has a character like ^M at the end of the line. I would like to exclude that when comparing. I also need to find the number of lines that matched. Here is my code. How to add that ^M and where to increment the line contor?

int compareFile(FILE* file_compared, FILE* file_checked)
{
    bool diff = 0;
    int N = 65536;
    char* b1 = (char*) calloc (1, N+1);
    char* b2 = (char*) calloc (1, N+1);
    size_t s1, s2;

    do {
        s1 = fread(b1, 1, N, file_compared);
        s2 = fread(b2, 1, N, file_checked);

        if (s1 != s2 || memcmp(b1, b2, s1)) {
            diff = 1;
            break;
        }
      } while (!feof(file_compared) || !feof(file_checked));

    free(b1);
    free(b2);

    if (diff) return 0;
    else return 1;
}

void main(int argc, char *argv[] )
{
FILE *fpread, *fpread2;
  char filebuff[MAXLINE];
  char filebuff2[MAXLINE];
  int var = 0;
  int linecount = 0;
printf ("COMPARE RESULT %d \n",compareFile("file1","file2"));

Upvotes: 1

Views: 2183

Answers (2)

unwind
unwind

Reputation: 400109

What you see as ^M is in fact the carriage return character (ASCII 13, C syntax \r). When comparing text files, it's best to not care about the line termination mode used, since there are several (Unix, Windows and Mac each has their own).

You should probably split the input into lines, ignoring the exact line-termination used, and compare the lines.

UPDATE Write a function that reads one character at a time, stopping when it reaches any valid line-termination sequence, and make sure to dynamically allocate memory as the line grows.

Upvotes: 1

Rami Jarrar
Rami Jarrar

Reputation: 4643

At the first:

int diff = 0;

increment the counter:

if (s1 != s2 || memcmp(b1, b2, s1)) {
    ++diff;
}

and at the last just this:

return diff;

Also your function should be:

int compareFile(char* fc_name,char* fk_name){
    /* Variable Declarations */
    FILE *file_compared = fopen(fc_name,"r");
    FILE *file_checked = fopen(fk_name,"r");
    if(file_compared == NULL || file_checked == NULL)
          return -1;
    /* .... */
}

Upvotes: 0

Related Questions