Compare two files

前端 未结 6 1648
一向
一向 2020-12-14 03:57

I\'m trying to write a function which compares the content of two files.

I want it to return 1 if files are the same, and 0 if different.

ch1 an

6条回答
  •  心在旅途
    2020-12-14 04:18

    Better to use fread and memcmp to avoid \0 character issues. Also, the !feof checks really should be || instead of && since there's a small chance that one file is bigger than the other and the smaller file is divisible by your buffer size..

    int compareFile(FILE* f1, FILE* f2) {
      int N = 10000;
      char buf1[N];
      char buf2[N];
    
      do {
        size_t r1 = fread(buf1, 1, N, f1);
        size_t r2 = fread(buf2, 1, N, f2);
    
        if (r1 != r2 ||
            memcmp(buf1, buf2, r1)) {
          return 0;
        }
      } while (!feof(f1) || !feof(f2));
    
      return 1;
    }
    

提交回复
热议问题