Code reuse without obfuscation
Hi all -- long time no see,
I have a little C assignment from a training program I'm in. I'm used to C++. My program is essentially two methods in main() that do very similar things to two arrays of structures (different structures). In C++, I could combine these two tasks into one template function, the only fundamental difference being the two different structure types. Is there any way to generalize this code so that it need be expressed only once, or will I do more harm than good? I'm wondering for the sake of C, with which I am not familiar. Here is most of main():
Code:
/* If only C had templates like C++.... */
/* These two sections of code are similar. */
/* read stock file */
stock_file = fopen(argv[1], "r");
if(stock_file == NULL)
fopen_abort(argv[1]);
stock_file_nlines = n_lines(stock_file);
stocks = (stock*)calloc(stock_file_nlines, sizeof(stock));
if(stocks == NULL)
memory_abort();
n_stocks = read_stocks(stock_file, stocks);
qsort(stocks, n_stocks, sizeof(stock), stock_cmp);
/* process trades in trade file */
trade_file = fopen(argv[2], "r");
if(trade_file == NULL)
{
free(stocks);
fopen_abort(argv[2]);
}
trade_file_nlines = n_lines(trade_file);
trades = (trade*)calloc(trade_file_nlines, sizeof(trade));
if(trades == NULL)
memory_abort();
n_trades = process_trades(trade_file, trades, stocks, n_stocks);
qsort(trades, n_trades, sizeof(trade), trade_cmp);
I see how I could consolidate the file-opening and fopen() error checking, but what about the rest?
Thanks.