Home Segments Index Top Previous Next

600: Mainline

Combining the argument-testing statements into the analyze_trades program, you have the following:

#include   
/* Define the trade structure */ 
struct trade {double price; int number;}; 
/* Define value-computing function */ 
double trade_price (struct trade *tptr) { 
  return tptr -> price * tptr -> number; 
} 
/* Define trade array */ 
struct trade *trade_pointers[100]; 
main (int argument_count, char **argument_array) { 
  /* Declare various variables */ 
  int limit, counter, number; 
  double price, sum = 0.0; 
  /* Declare trade_source, a pointer to a file-describing structure */ 
  FILE* trade_source; 
  /* Test argument count */ 
  if (argument_count != 2) { 
    printf ("Sorry, %s requires exactly one argument.\n",  
            argument_array [0]); 
    exit (0); 
  } 
  /* Prepare a file-describing structure for reading */ 
  trade_source = fopen (argument_array[1], "r"); 
  /* Make sure file opened properly */ 
  if (trade_source == NULL) { 
    printf ("Sorry, %s is not a file name.\n", argument_array [1]); 
    exit (0); 
  } 
  /* Read numbers from the file and stuff them into array */ 
  for (limit = 0; 
       2 == fscanf (trade_source, "%lf%i", &price, &number); 
       ++limit) { 
    trade_pointers[limit] 
      = (struct trade*) malloc (sizeof (struct trade)); 
    trade_pointers[limit] -> price = price; 
    trade_pointers[limit] -> number = number; 
  } 
  /* Close source file */ 
  fclose (trade_source); 
  /* Find value of shares traded */ 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + trade_price(trade_pointers[counter]); 
  /* Display value of shares traded */ 
  printf ("The total value of the %i trades is %f.\n", 
                                  limit,       sum); 
}