I’m novice programmer and am writing a simple wav-player in C as a pet project. Part of the file loading process requires reading specific data (sampling rate, number of channels,…) from the file header.
Currently what I’m doing is similar to this:
- Scan for a sequence of bytes and skip past it
- Read 2 bytes into variable a
- Check value and return on error
- Skip 4 bytes
- Read 4 bytes into variable b
- Check value and return on error
…and so on. (code see: https://github.com/qgi/Player/blob/master/Importer.c)
I’ve written a number of helper functions to do the scanning/skipping/reading bit. Still I’m repeating the reading, checking, skipping part several times, which doesn’t seem to be neither very effective nor very smart. It’s not a real issue for my project, but as this seems to be quite a common task when handling binary files, I was wondering:
Is there some kind of a pattern on how to do this more effectively with cleaner code?
Most often, people define structs (often with something like
#pragma pack(1)to assure against padding) that matches the file’s structures. They then read data into an instance of that with something likefread, and use the values from the struct.