Home Segments Index Top Previous Next

556: Mainline

Collecting what you have just learned about file input and output, you easily can amend programs that read from your keyboard and display on your screen such that they read from a file and write to a file. The following program, for example, fills an array with trade objects using information from a file named test.data, and then writes the result of its analysis of those trade objects into a file named test.result:

#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 ( ) { 
  /* Declare various variables */ 
  int limit, counter, number; 
  double price, sum = 0; 
  /* Define trade_source, a pointer to a file structure */ 
  FILE* trade_source; 
  /* Define analysis_target, a pointer to a file structure */ 
  FILE* analysis_target; 
  /* Prepare a file structure for reading */ 
  trade_source = fopen ("test.data", "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); 
  /* Find value of shares traded */ 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + trade_price(trade_pointers[counter]); 
  /* Prepare a file structure for writing*/ 
  analysis_target = fopen("test.result", "w"); 
  /* Write value of shares traded */ 
  fprintf (analysis_target, 
           "The total value of the %i trades is %f.\n", 
                                   limit,       sum); 
  /* Close target file */ 
  fclose (analysis_target); 
}