Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // arbitrary buffer size for reading file input
  5. #define BUFSIZE 1000
  6.  
  7. int find_array_maxes(int *input_array, int size){
  8. int max = 0;
  9. for(int i=0; i < size; i++){
  10. if(max < input_array[i]){
  11. max = input_array[i];
  12. }
  13. }
  14. return max;
  15. }
  16.  
  17. int main(int argc, char *argv[]){
  18. // check to ensure there are sufficient command line arguments
  19. if(argc <= 2){
  20. printf("At least two arguments are required!\n");
  21. exit(1);
  22. }
  23.  
  24. // allocates memory for array that will store file values
  25. int array_size = atoi(argv[1]);
  26. int *array_ptr = (int*) malloc(array_size * sizeof(int));
  27.  
  28. // creates a file ptr and buffer to read file contents
  29. FILE *file = fopen(argv[2], "r");
  30. char buff[BUFSIZE];
  31. int converted_num;
  32. int counter = 0;
  33.  
  34. // verify the array is allocated
  35. if(array_ptr == NULL){
  36. printf("Memory allocation of %d bytes has failed.\n", *array_ptr);
  37. fclose(file);
  38. exit(1);
  39. } else {
  40. // stores contents of file into the buffer and is converted from the buffer to int
  41. // to be stored in the dynamically allocated array
  42. while(fgets(buff, BUFSIZE-1, file) != NULL && counter < array_size){
  43. converted_num = atoi(buff);
  44. *array_ptr = converted_num;
  45. printf("%d\n", *array_ptr);
  46. array_ptr++;
  47. counter++;
  48. }
  49. fclose(file);
  50. }
  51. printf("The max number of the array is %d\n",find_array_maxes(array_ptr, array_size));
  52. return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement