Advertisement
Guest User

Untitled

a guest
Jan 13th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stddef.h>
  4. #include <float.h>
  5.  
  6. // Visual Studio: to skip warning message for safe functions.
  7. // Else delete pragma.
  8. #pragma warning(disable:4996)
  9.  
  10. float next_data(FILE* source);
  11. void append_info(FILE* source, FILE* dest);
  12.  
  13. int main()
  14. {
  15. FILE* output_file = fopen("output.txt", "a");
  16.  
  17. while (1)
  18. {
  19. char file_path[512];
  20. printf("\nEnter filepath to read values from or 'n' to quit: \n");
  21. scanf("%s", file_path);
  22.  
  23. if (file_path[0] == 'n')
  24. break;
  25.  
  26. FILE* source_file = fopen(file_path, "r");
  27. if (!source_file)
  28. {
  29. printf("\nNo such file!\n");
  30. break;
  31. }
  32.  
  33. append_info(source_file, output_file);
  34. fclose(source_file);
  35. }
  36.  
  37.  
  38. fclose(output_file);
  39. return EXIT_SUCCESS;
  40. }
  41.  
  42. float next_data(FILE* source)
  43. {
  44. float input = 0;
  45. fscanf(source, "%f", &input);
  46.  
  47. return input;
  48. }
  49.  
  50. void append_info(FILE* source, FILE* dest)
  51. {
  52. float min = FLT_MAX, max = -FLT_MAX; // no std::numeric_limits so fuck this language tbh
  53. float sum = 0, avg = 0;
  54. size_t elem_count = 0;
  55.  
  56. while(!feof(source))
  57. {
  58. float curr = next_data(source);
  59. ++elem_count;
  60.  
  61. if (curr < min)
  62. min = curr;
  63. if (curr > max)
  64. max = curr;
  65.  
  66. sum += curr;
  67. }
  68.  
  69. if (!elem_count)
  70. {
  71. fprintf(dest, "%s", "\nNo data.\n");
  72. return;
  73. }
  74.  
  75. avg = sum / elem_count;
  76. fprintf(dest, "min: %f, max: %f, avg: %f\n", min, max, avg);
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement