比较两个文件是否相同(C/C++语言)
1 #include <stdio.h> 2 #include <string.h> 3 const int max_r = 1024; 4 5 // Calculate the file size 6 void Get_file_size(char *name_1, char *name_2) 7 { 8 FILE *fp_1 = fopen(name_1, "r"); 9 FILE *fp_2 = fopen(name_2, "r"); 10 if (fp_1) 11 { 12 printf ("Size of %s : ", name_1); 13 fseek(fp_1, 0, SEEK_END); 14 if (1.*ftell(fp_1)/(1024*1024*1024) > 1.0) 15 printf("%.1f GB\n", 1.*ftell(fp_1)/(1024*1024*1024)); 16 else if(1.*ftell(fp_1)/(1024*1024) > 1.0) 17 printf("%.1f MB\n", 1.*ftell(fp_1)/(1024*1024)); 18 else if (1.*ftell(fp_1)/(1024) > 1.0) 19 printf("%.1f KB\n", 1.*ftell(fp_1)/(1024)); 20 else printf ("%d Bt\n", ftell(fp_1)); 21 fclose(fp_1); 22 } 23 if (fp_2) 24 { 25 printf ("Size of %s : ", name_2); 26 fseek(fp_2, 0, SEEK_END); 27 if (1.*ftell(fp_2)/(1024*1024*1024) > 1.0) 28 printf("%.1f GB\n", 1.*ftell(fp_2)/(1024*1024*1024)); 29 else if(1.*ftell(fp_2)/(1024*1024) > 1.0) 30 printf("%.1f MB\n", 1.*ftell(fp_2)/(1024*1024)); 31 else if (1.*ftell(fp_2)/(1024) > 1.0) 32 printf("%.1f KB\n", 1.*ftell(fp_2)/(1024)); 33 else printf ("%d Bt\n", ftell(fp_2)); 34 fclose(fp_2); 35 } 36 return; 37 } 38 39 int main() 40 { 41 int AC, line_1, line_2; 42 char name_1[100], name_2[100]; 43 char ch_1[max_r], ch_2[max_r]; 44 45 scanf ("%s%s", name_1, name_2);//input two file which need to be compared 46 AC = 1; 47 line_1 = line_2 = 0; 48 Get_file_size(name_1, name_2); 49 50 FILE *fp_1 = fopen(name_1, "r"); 51 FILE *fp_2 = fopen(name_2, "r"); 52 while(1) 53 { 54 char *end_1, *end_2; 55 end_1 = fgets(ch_1, max_r, fp_1); 56 end_2 = fgets(ch_2, max_r, fp_2); 57 if (end_1 != NULL) 58 line_1 ++; 59 if (end_2 != NULL) 60 line_2 ++; 61 while(strcmp(ch_1, "\n") == 0 && end_1 != NULL) 62 { 63 end_1 = fgets(ch_1, max_r, fp_1); 64 if (end_1 != NULL) 65 line_1 ++; 66 } 67 while(strcmp(ch_2, "\n") == 0 && end_2 != NULL) 68 { 69 end_2 = fgets(ch_2, max_r, fp_2); 70 if (end_2 != NULL) 71 line_2 ++; 72 } 73 if (end_1 == NULL && end_2 == NULL) 74 break; 75 if(strcmp(ch_1, ch_2) != 0) 76 { 77 AC = 0; 78 ch_1[strlen(ch_1) -1] = '\0'; 79 ch_2[strlen(ch_2) -1] = '\0'; 80 printf (" Worry Answer\n"); 81 printf ("In file %s at %d line << %s >> difference from\n", name_1, line_1, ch_1); 82 printf ("In file %s at %d line << %s >>\n", name_2, line_2, ch_2); 83 break; 84 } 85 } 86 if (AC) 87 { 88 if (line_1 != line_2) 89 { 90 printf (" Print Error\n"); 91 printf ("The print not in a canonical format!\n"); 92 printf ("the %s have %d lines \nbut %s have %d lines!\n", name_1, line_1, name_2, line_2); 93 } 94 else 95 printf (" Aceept\n", line_1, line_2); 96 } 97 fclose(fp_1); 98 fclose(fp_2); 99 return 0; 100 }