anonymm
anonymm

Reputation: 11

Comparing files with C

I'm trying to write a code that compares two files and shows if they are equal or not

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

int main(){
    
    FILE *f1, *f2;
    int diff = 0;
    char c1, c2, name_f1[100], name_f2[100];

    printf("File1: ");
    fgets(name_f1, 100, stdin);

    printf("File2: ");
    fgets(name_f2, 100, stdin);

    f1 = fopen(name_f1, "r+");
    f2 = fopen(name_f2, "r+");
    
    do{
        c1 = fgetc(f1);
        c2 = fgetc(f2);

        if (c1 != c2){
            diff = 1;
        }
    }while(c1 != EOF && c2 != EOF);

    fclose(f1);
    fclose(f2);

    if(diff==1){
        printf("Files are different");
    }else{
        printf("Files are the same");
    }

    return 0;
}

But it keeps telling me that they are the same, even if they are not and I have no idea why Also if fopen is just for reading ("r") it return segmentation fault, which I also have no idea why is happening

Any help is appreciated, thanks.

Upvotes: 0

Views: 55

Answers (1)

Omer Kawaz
Omer Kawaz

Reputation: 300

the behavior you're describing might suggest the files you're trying to open don't exist, since "r" returns null if the file doesn't exist but "r+" creates a file*, this does seem to explain the segmentation fault error.
therefor it's also reasonable you're program returns the files are identical, since both created files will be empty. perhaps you're path isn't correct?

Tip: always check for fopen success and exit on failure

*as seen here: https://www.geeksforgeeks.org/file-opening-modesr-versus-r/

Upvotes: 2

Related Questions