C course - final course example puts it all together
Archive - Originally posted on "The Horse's Mouth" - 2010-07-02 18:14:01 - Graham Ellis
"Yes - but how do we put all of those things together?" ... delegate question on many programming courses. As a trainer, I have to take our students through each of the main features of a language - to ensure they understand the fundamentals and perhaps more. But the it's just as important to take time before the course ends to pull all the threads together and show a complete, practical, maintainable and robust piece of code.
So here I am, on a Friday evening. Delegates have headed off to places as wide ranging as Norwich and Exeter, and I'm writing up the example that I completed just before they left. [source code link].
The example program reads one of our recent log file - they're currently around 40 Mbytes per day - and uses regular expressions to filter out all of those accesses which were arrivals from a well know search engine.
We have no way of knowing how long search strings will be, nor how many arrivals we'll have, so the memory management needs to be dynamic and use the heap ... so our example's got to include things like malloc calloc and realloc. And we have various string manipulation functions in use to find, extract and save on the heap the elements we need from each line.
Why would people use C for an application such as this? Perhaps because they knew the language already, or perhaps because they needed to run it so often and on so much material that it had to be FAST. And so you'll notice that in order to get the speed, we've compiled our regular expressions outside our main data reading loop, and we've also extended our heap memory block in chunks of 10 records at a time. The simplest coding would have been to extend the capacity one at a time, but this would have been very slow. 100 at a time would probably be better!
If you want to learn C next time I teach the course, have a look [here] if you've never programmed before and [here] if you'll be converting from another language. I'm not promising you'll be able to quickly write code like my example by the end of the course - that requires a bit more practice - but I can promise you that you'll understand what's going on, you'll be able to fathom out some previously unfathomable code, and you'll be well on the way to becoming a C programmer.