Home Segments Index Top Previous Next

598: Mainline

Now you can combine what you know about command-line arguments with what you know about opening files so as to supply a file name to a program that actually reads from the file. For example, the following, revised version of analyze_trades works on a command-line argument, rather than on a wired-in file name:

#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; 
  /* Prepare a file-describing structure for reading */ 
  trade_source = fopen (argument_array[1], "r"); 
  /* 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); 
  // Analyze data 
}