compare.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Tema 2 ASC
  3. * 2020 Spring
  4. * !!! Do not modify this file !!!
  5. */
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <stdint.h>
  9. #include <fcntl.h>
  10. #include <sys/stat.h>
  11. #include <sys/mman.h>
  12. #include <unistd.h>
  13. #include <math.h>
  14. #define check_err(a,b,err) ((fabs((a) - (b)) <= (err)) ? 0 : -1)
  15. /*
  16. * Compares two upper matrixes withtin a tolerance limit
  17. */
  18. int cmp_files(char const *file_path1, char const *file_path2, double precision) {
  19. struct stat fileInfo1, fileInfo2;
  20. double *mat1, *mat2;
  21. int i, j, fd1, fd2, N, ret = 0;
  22. fd1 = open(file_path1, O_RDONLY, (mode_t)0600);
  23. fd2 = open(file_path2, O_RDONLY, (mode_t)0600);
  24. fstat(fd1, &fileInfo1);
  25. fstat(fd2, &fileInfo2);
  26. if(fileInfo1.st_size != fileInfo2.st_size) {
  27. printf("Files length differ\n");
  28. close(fd1);
  29. close(fd2);
  30. return -1;
  31. }
  32. mat1 = mmap(0, fileInfo1.st_size, PROT_READ, MAP_SHARED, fd1, 0);
  33. if (mat1 == MAP_FAILED)
  34. {
  35. close(fd1);
  36. close(fd2);
  37. printf("Error mmapping the first file");
  38. return -1;
  39. }
  40. mat2 = mmap(0, fileInfo2.st_size, PROT_READ, MAP_SHARED, fd2, 0);
  41. if (mat2 == MAP_FAILED)
  42. {
  43. munmap(mat1, fileInfo1.st_size);
  44. close(fd1);
  45. close(fd2);
  46. printf("Error mmapping the second file");
  47. return -1;
  48. }
  49. N = sqrt(fileInfo1.st_size / sizeof(double));
  50. for (i = 0; i < N; i++ ) {
  51. for (j = 0; j< N; j++) {
  52. ret = check_err(mat1[i * N + j], mat2[i * N + j], precision);
  53. if (ret != 0) {
  54. printf("Matrixes differ on index [%d, %d]. Expected %.8lf got %.8lf\n",
  55. i, j, mat1[i * N + j], mat2[i * N + j]);
  56. goto done;
  57. }
  58. }
  59. }
  60. done:
  61. munmap(mat1, fileInfo1.st_size);
  62. munmap(mat2, fileInfo2.st_size);
  63. close(fd1);
  64. close(fd2);
  65. return ret;
  66. }
  67. int main(int argc, const char **argv)
  68. {
  69. double precision;
  70. int ret = 0;
  71. if(argc < 4) {
  72. printf("Usage: %s mat1 mat2 tolerance\n",argv[0]);
  73. exit(0);
  74. }
  75. sscanf(argv[3], "%lf", &precision);
  76. ret = cmp_files(argv[1],argv[2],precision);
  77. printf("%s %s %s %s\n", argv[0], argv[1], argv[2], (ret == 0 ? "OK" : "Incorrect results!"));
  78. return 0;
  79. }